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

Optimize values() calls #5479

Draft
wants to merge 1 commit into
base: develop
Choose a base branch
from
Draft

Optimize values() calls #5479

wants to merge 1 commit into from

Conversation

brimoor
Copy link
Contributor

@brimoor brimoor commented Feb 8, 2025

Change log

This PR experiments with optimizing values("id") calls.

Currently, values("id") executes the following pipeline:

pipeline = [
    {
        "$project": {
            "value": {
                "$cond": {
                    "if": {"$gt": ["$_id", None]},
                    "then": {"$toString": "$_id"},
                    "else": None,
                },
            },
        },
    },
]

I wanted to see how much faster values("id") would be if the following pipeline were instead used:

pipeline = [{"$project": {"_id": 1}}]

with the str() conversion instead happening in Python rather than in the database.

Additionally, values("id") does not leverage the _id field index in either of the above pipelines by default. It uses a COLLSCAN. So, I also wanted to see how much faster/slower both pipelines are when they use an IXSCAN, which can be forced via hint={"_id": 1}.

Findings

The benchmarking section below shows the following findings on a local database with a 500k sample dataset:

  • The {"$project": {"_id": 1}} pipeline runs in 2.1 seconds compared to the original pipeline, which runs in 3.4 seconds
  • Interestingly, adding hint={"_id": 1} makes both pipelines 0.4-0.6 seconds slower

Create large dataset

import numpy as np

import fiftyone as fo
import fiftyone.zoo as foz

def expand_dataset(dataset, target_num_samples):
    num_doubles = int(np.ceil(np.log2(target_num_samples / len(dataset))))
    with fo.ProgressBar(start_msg="Expanding dataset") as pb:
        for i in pb(list(range(1, num_doubles + 1))):
            # Cloning avoids the halloween problem, which I observed if directly using `dataset` in-place of `tmp` here
            # https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge/#output-to-the-same-collection-that-is-being-aggregated
            if i == num_doubles:
                tmp = dataset[:(target_num_samples - len(dataset))].clone()
            else:
                tmp = dataset.clone()

            dataset.add_collection(tmp, new_ids=True)
            tmp.delete()

dataset = foz.load_zoo_dataset(
    "cifar10",
    split="train",
    dataset_name="zzz",
    persistent=True,
)

expand_dataset(dataset, 500000)

Test real usage

import fiftyone as fo
import eta.core.utils as etau

dataset = fo.load_dataset("zzz")
dataset.clone_sample_field("id", "id2")
# dataset.create_index("id2")

# Uses optimized values() call
# Time elapsed: 2.7 seconds
with etau.Timer():
    _ = dataset.values("id")

# Using existing values() call
# Time elapsed: 3.8 seconds
with etau.Timer():
    _ = dataset.values("id2")

Benchmarking

import fiftyone as fo
import eta.core.utils as etau

dataset = fo.load_dataset("zzz")

# Current behavior: in-database string conversion
# Time elapsed: 2.8 seconds
with etau.Timer():
    pipeline = [
        {
            "$project": {
                "value": {
                    "$cond": {
                        "if": {"$gt": ["$_id", None]},
                        "then": {"$toString": "$_id"},
                        "else": None,
                    },
                },
            },
        },
    ]
    results = dataset._sample_collection.aggregate(pipeline)
    ids = [d["value"] for d in results]

# With field inclusion
# Time elapsed: 2.1 seconds
with etau.Timer():
    pipeline = [{"$project": {"_id": 1}}]
    results = dataset._sample_collection.aggregate(pipeline)
    ids = [d["_id"] for d in results]
    ids = [str(_id) for _id in ids]

# With field inclusion + index hint
# Time elapsed: 2.5 seconds
with etau.Timer():
    pipeline = [{"$project": {"_id": 1}}]
    results = dataset._sample_collection.aggregate(pipeline, hint={"_id": 1})
    ids = [d["_id"] for d in results]
    ids = [str(_id) for _id in ids]

# With field setting + hint
# Time elapsed: 3.4 seconds
with etau.Timer():
    pipeline = [{"$project": {"value": "$_id"}}]
    results = dataset._sample_collection.aggregate(pipeline, hint={"_id": 1})
    ids = [d["value"] for d in results]
    ids = [str(_id) for _id in ids]

@brimoor brimoor requested a review from kaixi-wang February 8, 2025 20:26
Copy link
Contributor

coderabbitai bot commented Feb 8, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


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.

@kaixi-wang
Copy link
Contributor

kaixi-wang commented Feb 16, 2025

Interesting... the project _id and hint at the db level I would expect to be doing the same thing (the 3rd case of using a new field I would expect to take longer/not be able to use the hint because the directly projected field isn't indexed) ...

When I run it, even on a small dataset (10 samples), hint is always faster...
image
image

I'll check the explain plans/do a little more investigating

self._field = self._manual_field or field
self._big_field = big_field
self._num_list_fields = len(list_fields)
# Optimization: call str() in memory rather than $toString in database
Copy link
Contributor

Choose a reason for hiding this comment

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

not really related to this PR, but would it be possible to not convert it to string? or would that break a lot of things/not be easy to change?

Just thinking about in-memory conversion to string (if done not while iterating over the cursor but done in a list comprehension) doesn't scale well for millions of samples

Copy link
Contributor Author

Choose a reason for hiding this comment

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

values("id") returns strings, values("_id") returns ObjectIDs. So it is up to the caller on whether they want to potentially optimize things by directly working with ObjectIDs rather than strings.

You're right that it should be slightly faster to use ObjectIDs. It removes the $toString conversion in the database, and ObjectId is fewer bytes than str(ObjectId) so it would decrease network I/O somewhat.

# Optimization: use field inclusion syntax when possible
if self._expr is None and path == "_id":
big_field = path
_pipeline = [{"$project": {"_id": 1}}]
Copy link
Contributor

Choose a reason for hiding this comment

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

What is big_field? I think I looked into it once, and it looked like it was just used for frames... I may be wrong, but I don't think frame _ids are used much, just sample_id, frame_number, and in that case, we should project those fields

Copy link
Contributor Author

Choose a reason for hiding this comment

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

values() is a "big" aggregation because it returns IDs one at a time (in separate documents). All other aggregations are true aggregations: they do the combination in the database and return the results in a single document (ie min(), max(), etc).

Returning values() results as "big" style aggregations is necessary to avoid errors when the dataset contains >16MB of IDs.

@kaixi-wang
Copy link
Contributor

Also the results on 11million samples:
image

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.

2 participants