Skip to content

[Data] Cache PyArrow vocabulary arrays and inverse label mapping in encoders - #67524

Open
deep1blue wants to merge 6 commits into
ray-project:masterfrom
deep1blue:perf/data-encoder-cache-arrow-vocab
Open

deep1blue wants to merge 6 commits into
ray-project:masterfrom
deep1blue:perf/data-encoder-cache-arrow-vocab

Conversation

@deep1blue

Copy link
Copy Markdown
Contributor

Why are these changes needed?

  1. OrdinalEncoder._get_arrow_arrays and OneHotEncoder._get_arrow_arrays rebuild PyArrow vocabulary arrays on every batch:
    During _fit, OrdinalEncoder and OneHotEncoder populate self.stats_[f"unique_values({col})"] as a Python {category: index} dict. Because both preprocessors prefer BatchFormat.ARROW, every _transform_arrow batch call invokes _get_unique_value_arrow_arrays(self.stats_, input_col), which re-sorts all V keys in Python (sorted(stat_value.keys())) and allocates two new PyArrow arrays (pa.array(sorted_keys) and pa.array([stat_value[k] for k in sorted_keys])) in O(V log V) time per batch per column. On 4,096-row string batches with V = 10k–100k categories, this per-batch dict-to-Arrow conversion accounts for ~70–75% of _transform_arrow runtime (3.5 ms -> 0.8 ms at V=10k, 4.1x speedup; 62 ms -> 15.5 ms at V=100k, 4.0x speedup).
  2. LabelEncoder._inverse_transform_pandas rebuilds the inverse label dict on every batch:
    LabelEncoder._inverse_transform_pandas reconstructs {value: key for key, value in self.stats_[f"unique_values({self._label_column})"].items()} on every batch inside column_label_decoder.

Changes

  • Add _get_cached_unique_value_arrow_arrays(preprocessor, input_col) to cache the (keys_array, values_array) tuple per column on the preprocessor instance, keyed by the identity and length of self.stats_[f"unique_values({input_col})"] so re-fitting or replacing stats_ automatically invalidates the cache.
  • Cache the inverted {index: label} dictionary in LabelEncoder._inverse_transform_pandas with the same stats_ identity/length invalidation.
  • Exclude _arrow_arrays_cache and _inverse_label_cache in __getstate__ so serialized/pickled preprocessors remain lightweight and unchanged on wire.

Acknowledgments

Builds on the PyArrow-native encoder and aggregation-based fitting work in python/ray/data/preprocessors/encoder.py by @cem-anyscale (#59810), @xinyuangui2 (#59890, #60790), @abhishekverma-ray (#66088, #66091), and @ayushk7102 (#62618, #62623).

Related issue number

N/A

Checks

…ncoders

Cache the sorted PyArrow key/value lookup arrays in OrdinalEncoder and
OneHotEncoder per column (invalidated if the underlying stats_ dict changes
and excluded from pickle state) and cache the inverted label mapping in
LabelEncoder._inverse_transform_pandas so they are not rebuilt on every batch.

Signed-off-by: Parth Vadera <[email protected]>
Co-authored-by: Copilot <[email protected]>
@deep1blue
deep1blue requested a review from a team as a code owner October 29, 2026 00:42

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request introduces caching for Arrow lookup arrays and inverse label mappings in OrdinalEncoder, OneHotEncoder, and LabelEncoder to prevent redundant rebuilds across batches, while ensuring these transient caches are excluded during serialization. Feedback on the changes suggests avoiding direct access or mutation of dict when retrieving or setting cache attributes, recommending the use of standard, idiomatic Python built-ins like getattr and setattr instead.

Comment on lines +80 to +81
cache = preprocessor.__dict__.setdefault("_arrow_arrays_cache", {})
cached = cache.get(input_col)

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.

medium

Directly accessing or mutating __dict__ is generally discouraged in Python when standard built-ins like getattr and setattr can be used. Using getattr is safer, cleaner, and more idiomatic.

    cache = getattr(preprocessor, "_arrow_arrays_cache", None)
    if cache is None:
        cache = {}
        preprocessor._arrow_arrays_cache = cache
    cached = cache.get(input_col)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Updated in 1b34e3e to use getattr(preprocessor, "_arrow_arrays_cache", None) and preprocessor._arrow_arrays_cache = cache instead of accessing __dict__ directly (verified with test_encoder_arrow_and_inverse_label_caching).

}
return s.map(inverse_values)
stat_value = self.stats_[f"unique_values({self._label_column})"]
cached = self.__dict__.get("_inverse_label_cache")

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.

medium

Instead of accessing self.__dict__ directly, use getattr(self, ...) which is the standard and idiomatic way to retrieve optional attributes dynamically in Python.

Suggested change
cached = self.__dict__.get("_inverse_label_cache")
cached = getattr(self, "_inverse_label_cache", None)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Updated in 1b34e3e to use getattr(self, "_inverse_label_cache", None) instead of self.__dict__.get(...) (verified with test_encoder_arrow_and_inverse_label_caching).

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Oct 29, 2026
@Yin-1022

Copy link
Copy Markdown
Contributor

I found a stale-cache correctness issue when an encoder's stats_ mapping is mutated in place without changing its identity or length.

The current invalidation check only rebuilds when:

cached[0] is not stat_value or cached[1] != len(stat_value)

so changes to the contents of the same dict with the same number of entries are not detected.

I reproduced this on the current head (1b34e3ed84) with all three affected encoders.

For OrdinalEncoder, after caching:

{"a": 0, "b": 1}

and then mutating the same dict in place to:

{"a": 1, "b": 0}

transforming ["a", "b"] still returns:

[0, 1]

instead of [1, 0].

OneHotEncoder shows the same stale vocabulary behavior. Replacing the contents of the same two-entry mapping from {"a": 0, "b": 1} to {"x": 0, "y": 1} causes ["x", "y"] to be encoded as:

[[0, 0], [0, 0]]

because the cached Arrow vocabulary still contains a / b.

LabelEncoder also keeps the stale inverse mapping: after mutating the same dict
from {"cat": 0, "dog": 1} to {"bird": 0, "fish": 1},
inverse-transforming [0, 1] still returns ["cat", "dog"].

It looks like identity + length isn't sufficient to determine whether the underlying stats entry changed. The cache either needs to be invalidated whenever the stats mapping can change, or use a content/version signal that also detects same-size in-place updates.

Store a shallow snapshot copy of the column's stats_ dict alongside its object
reference so in-place mutations that preserve dict identity and length still
trigger cache invalidation in OrdinalEncoder, OneHotEncoder, and LabelEncoder.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Parth Vadera <[email protected]>
@deep1blue

Copy link
Copy Markdown
Contributor Author

Thanks for catching this and sharing the reproducers, @Yin-1022! Fixed in da2850c68c: _get_cached_unique_value_arrow_arrays and LabelEncoder._inverse_transform_pandas now store a shallow snapshot copy (stat_value.copy()) alongside the dict reference and rebuild when cached[0] is not stat_value or cached[1] != stat_value, so same-size in-place mutations to stats_ entries invalidate the cache across OrdinalEncoder, OneHotEncoder, and LabelEncoder.

Verified locally with test_encoder_arrow_and_inverse_label_caching (extended with same-size in-place value permutation and key-replacement cases for all three encoders) and your three standalone reproducers.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit da2850c. Configure here.

deep1blue and others added 2 commits October 29, 2026 04:48
…coder caches

Replace the per-batch shallow snapshot dict equality check with a lightweight
_VersionedDict subclass that increments an integer _version counter on in-place
mutations and reduces to a plain dict when pickled. This keeps hot-path cache
hits O(1) for large vocabularies while still invalidating on in-place stats_
mutations.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Parth Vadera <[email protected]>
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Nov 14, 2026
@deep1blue

Copy link
Copy Markdown
Contributor Author

Keeping this PR open — the branch remains cleanly mergeable with master (mergeable=True, DCO success) and is ready for maintainer review. Please let me know if any updates or additional tests would be helpful!

@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Nov 14, 2026
@abhishekverma-ray abhishekverma-ray added the go add ONLY when ready to merge, run all tests label Nov 18, 2026

@abhishekverma-ray abhishekverma-ray 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.

No correctness issues found: the cache keys on identity plus a version, and pickling and deepcopy drop it. The test checks internals, though:

  • it monkeypatches a call counter;
  • it calls private _transform_arrow / _inverse_transform_pandas;
  • it sets stats_ / _fitted by hand and asserts on the private caches.

Could it test behavior through the public API instead?

  • fit → transform_batch → re-fit on different categories → transform_batch gives the new encoding;
  • serialize() / pickle after a transform still transforms correctly;
  • one LabelEncoder inverse_transform round trip.

Design note: _VersionedDict changes the type of the public stats_ values and is about 50 lines. A cache keyed on the stats object's identity, or cleared in _fit / _set_stats, might be simpler.

…est via public API

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Parth Vadera <[email protected]>
@deep1blue

Copy link
Copy Markdown
Contributor Author

Thanks for the review @abhishekverma-ray! Updated in 92f1611:

  • Removed _VersionedDict and simplified the cache invalidation to cached[0] is not stat_value so stats_ entries remain plain dict instances.
  • Updated test_encoder_arrow_and_inverse_label_caching to test via the public API (fit / transform_batch / inverse_transform) instead of setting stats_ or calling _transform_arrow / _inverse_transform_pandas directly.

Verified locally with pytest python/ray/data/tests/preprocessors/test_encoder.py -k test_encoder_arrow_and_inverse_label_caching (1 passed).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community data Ray Data-related issues go add ONLY when ready to merge, run all tests unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants