Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

beam.map() #5449

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open

beam.map() #5449

wants to merge 5 commits into from

Conversation

brimoor
Copy link
Contributor

@brimoor brimoor commented Jan 29, 2025

Change log

Adds a beam_map() method that leverages Apache Beam to apply a map_fcn to each sample in a sample_collection in parallel, optionally saving any sample edits and/or applying a reduce_fcn or aggregate_fcn to the outputs.

Example 1: map-save

import fiftyone as fo
import fiftyone.zoo as foz
import fiftyone.utils.beam as foub

dataset = foz.load_zoo_dataset("cifar10", split="train")
view = dataset.select_fields("ground_truth")

def map_fcn(sample):
    sample.ground_truth.label = sample.ground_truth.label.upper()

foub.beam_map(view, map_fcn, save=True, progress=True)

print(dataset.count_values("ground_truth.label"))
Batch 02/16: 100%|█████████████████████████████████████████████████████████████████████| 3125/3125 [00:03<00:00, 811.38it/s]
Batch 13/16: 100%|█████████████████████████████████████████████████████████████████████| 3125/3125 [00:03<00:00, 806.92it/s]
Batch 12/16: 100%|█████████████████████████████████████████████████████████████████████| 3125/3125 [00:03<00:00, 795.11it/s]
Batch 06/16: 100%|█████████████████████████████████████████████████████████████████████| 3125/3125 [00:03<00:00, 806.14it/s]
Batch 14/16: 100%|█████████████████████████████████████████████████████████████████████| 3125/3125 [00:03<00:00, 790.75it/s]
Batch 03/16: 100%|█████████████████████████████████████████████████████████████████████| 3125/3125 [00:03<00:00, 788.72it/s]
Batch 01/16: 100%|█████████████████████████████████████████████████████████████████████| 3125/3125 [00:03<00:00, 789.38it/s]
Batch 11/16: 100%|█████████████████████████████████████████████████████████████████████| 3125/3125 [00:03<00:00, 794.18it/s]
Batch 04/16: 100%|█████████████████████████████████████████████████████████████████████| 3125/3125 [00:03<00:00, 789.54it/s]
Batch 07/16: 100%|█████████████████████████████████████████████████████████████████████| 3125/3125 [00:03<00:00, 785.78it/s]
Batch 10/16: 100%|█████████████████████████████████████████████████████████████████████| 3125/3125 [00:03<00:00, 796.16it/s]
Batch 15/16: 100%|█████████████████████████████████████████████████████████████████████| 3125/3125 [00:03<00:00, 783.64it/s]
Batch 16/16: 100%|█████████████████████████████████████████████████████████████████████| 3125/3125 [00:03<00:00, 783.61it/s]
Batch 09/16: 100%|█████████████████████████████████████████████████████████████████████| 3125/3125 [00:03<00:00, 790.07it/s]
Batch 05/16: 100%|█████████████████████████████████████████████████████████████████████| 3125/3125 [00:03<00:00, 1008.09it/s]
Batch 08/16: 100%|█████████████████████████████████████████████████████████████████████| 3125/3125 [00:03<00:00, 1009.33it/s]
{'TRUCK': 5000, 'AIRPLANE': 5000, 'AUTOMOBILE': 5000, 'SHIP': 5000, 'FROG': 5000, 'BIRD': 5000, 'CAT': 5000, 'DEER': 5000, 'HORSE': 5000, 'DOG': 5000}

Same operation with iter_samples(autosave=True):

for sample in view.iter_samples(autosave=True, progress=True):
    map_fcn(sample)
 100% |██████████████████████████████████████████████████████████████████| 50000/50000 [27.6s elapsed, 0s remaining, 1.6K samples/s]      

Example 2: map-reduce

import fiftyone as fo
import fiftyone.zoo as foz
import fiftyone.utils.beam as foub

dataset = foz.load_zoo_dataset("cifar10", split="train")
view = dataset.select_fields("ground_truth")

def map_fcn(sample):
    return sample.ground_truth.label.lower()

class ReduceFcn(foub.ReduceFcn):
    def create_accumulator(self):
        from collections import Counter
        return Counter()

    def add_input(self, accumulator, input):
        sample_id, value = input
        accumulator[value] += 1
        return accumulator

    def merge_accumulators(self, accumulators):
        from collections import Counter
        accumulator = Counter()
        for a in accumulators:
            accumulator.update(a)
        return accumulator

    def extract_output(self, accumulator):
        counts = dict(accumulator)
        self._store_output(counts)

counts = foub.beam_map(view, map_fcn, reduce_fcn=ReduceFcn, progress=True)
print(counts)

Example 3: map-aggregate

import fiftyone as fo
import fiftyone.zoo as foz
import fiftyone.utils.beam as foub

dataset = foz.load_zoo_dataset("cifar10", split="train")
view = dataset.select_fields("ground_truth")

def map_fcn(sample):
    return sample.ground_truth.label.lower()

def aggregate_fcn(sample_collection, values):
    from collections import Counter
    return dict(Counter(values.values()))

counts = foub.beam_map(view, map_fcn, aggregate_fcn=aggregate_fcn, progress=True)
print(counts)

Summary by CodeRabbit

  • New Features

    • Introduced enhanced sample processing with Apache Beam for efficient mapping, reduction, and aggregation of large datasets. Users now enjoy configurable options including sharding, worker control, and progress reporting.
  • Chores

    • Integrated a new progress tracking dependency to provide improved user feedback during processing tasks.

@brimoor brimoor requested review from minhtuev and swheaton January 29, 2025 22:10
Copy link
Contributor

coderabbitai bot commented Jan 29, 2025

Walkthrough

This pull request introduces a new utility in the Apache Beam integration. The changes add a beam_map function that processes sample collections with mapping, reduction, or aggregation operations. New classes MapBatch and ReduceFcn manage batch processing and result reduction. Additionally, helper functions for key management are provided. The update also adds the tqdm dependency in setup.py for progress reporting.

Changes

File(s) Change Summary
fiftyone/.../beam.py Added beam_map function with support for map, map-reduce, and map-aggregate operations; introduced MapBatch and ReduceFcn classes for batch processing and reduction; added utility functions _set_key and _get_key.
setup.py Added "tqdm" as a new dependency in the INSTALL_REQUIRES list.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant beam_map
    participant ApacheBeam
    participant MapBatch
    participant ReduceFcn

    User->>+beam_map: Call beam_map(sample_collection, map_fcn, ...)
    beam_map->>+ApacheBeam: Set up pipeline with options
    ApacheBeam->>+MapBatch: Process sample batches using map_fcn
    MapBatch-->>-ApacheBeam: Return mapped results
    alt reduce/aggregate provided
        ApacheBeam->>+ReduceFcn: Combine results
        ReduceFcn-->>-ApacheBeam: Return aggregated output
    end
    ApacheBeam-->>-beam_map: Complete execution with processed samples
    beam_map-->>-User: Return final results
Loading

Poem

Oh, code so fresh, with hops so keen,
New functions and classes, a lively machine.
I nibble through samples, in a Beam of delight,
Aggregating results from morning to night.
With tqdm's progress, a smooth-running stream,
Here's to our changes—Hippity Hoppity, supreme!
🐰✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@brimoor brimoor force-pushed the beam-map branch 2 times, most recently from 21601b2 to 249a280 Compare February 3, 2025 14:56
@minhtuev
Copy link
Contributor

minhtuev commented Feb 5, 2025

I have done a little bit of refactor and bug fixes so that we can run evaluate detections with beam_map, the initial results look good :)

https://github.com/voxel51/fiftyone/pull/5471/files

@brimoor brimoor force-pushed the beam-map branch 2 times, most recently from a8aeeee to 11b1309 Compare February 9, 2025 05:56
@brimoor brimoor marked this pull request as ready for review February 22, 2025 18:45
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
fiftyone/utils/beam.py (1)

8-16: Remove unused import
The inspect module (line 8) is never referenced in this file. Removing it will help avoid clutter and remain consistent with best practices.

- import inspect
+ # import inspect  # remove this import statement
🧰 Tools
🪛 Ruff (0.8.2)

8-8: inspect imported but unused

Remove unused import: inspect

(F401)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ad05c8d and 2438eab.

📒 Files selected for processing (2)
  • fiftyone/utils/beam.py (3 hunks)
  • setup.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
fiftyone/utils/beam.py

8-8: inspect imported but unused

Remove unused import: inspect

(F401)


557-560: Use ternary operator reduce_cls = reduce_fcn if reduce_fcn is not None else ReduceFcn instead of if-else-block

Replace if-else-block with reduce_cls = reduce_fcn if reduce_fcn is not None else ReduceFcn

(SIM108)


581-582: Use a single with statement with multiple contexts instead of nested with statements

(SIM117)

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: test / test-python (ubuntu-latest-m, 3.11)
  • GitHub Check: test / test-python (ubuntu-latest-m, 3.10)
  • GitHub Check: test / test-python (ubuntu-latest-m, 3.9)
  • GitHub Check: e2e / test-e2e
  • GitHub Check: build
🔇 Additional comments (7)
fiftyone/utils/beam.py (6)

20-22: Environment variable usage
Setting GRPC_VERBOSITY to "NONE" effectively silences gRPC logs. This usage is fine for reducing log noise. No issues here.


349-361: Function signature clarity
The beam_map function signature is well-structured, with clearly named arguments matching the docstring. The choice to provide flexible parameters (reduce_fcn, aggregate_fcn, save) supports a wide range of data processing needs. Looks good!


362-461: Rich and instructive docstring
The docstring thoroughly explains various usage patterns (map-only, map-reduce, and map-aggregate) with clear examples. This level of detail is beneficial for maintainability and user adoption. Great work!


768-832: Parallel mapping implementation
The MapBatch class provides a parallel-friendly way to apply map_fcn to each sample. The conditional logic for slice-based vs. ID-based shards is clearly separated. Good job ensuring autosave=self.save is leveraged within the iteration.


833-893: Reducer design
The ReduceFcn class cleanly leverages the Apache Beam CombineFn interface to aggregate outputs. Storing the final results via _store_output() is straightforward and obvious. This design is flexible for custom reduce or aggregate operations.


894-904: Convenient intermediate results storage
_set_key and _get_key provide a neat way to store and retrieve intermediate results. Consider clarifying concurrency implications if multiple workers simultaneously set the same key. Otherwise, this method is well-conceived.

setup.py (1)

73-73: Good addition of tqdm
Including "tqdm" in the INSTALL_REQUIRES ensures that progress bars function correctly in the beam_map feature without requiring separate manual installation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants