Repository navigation
Conversation
…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]>
There was a problem hiding this comment.
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.
| cache = preprocessor.__dict__.setdefault("_arrow_arrays_cache", {}) | ||
| cached = cache.get(input_col) |
There was a problem hiding this comment.
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)There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
There was a problem hiding this comment.
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).
Co-authored-by: Copilot <[email protected]> Signed-off-by: Parth Vadera <[email protected]>
|
I found a stale-cache correctness issue when an encoder's 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 ( For {"a": 0, "b": 1}and then mutating the same dict in place to: {"a": 1, "b": 0}transforming instead of
because the cached Arrow vocabulary still contains
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]>
|
Thanks for catching this and sharing the reproducers, @Yin-1022! Fixed in Verified locally with |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit da2850c. Configure here.
…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]>
Co-authored-by: Copilot <[email protected]> Signed-off-by: Parth Vadera <[email protected]>
|
This pull request has been automatically marked as stale because it has not had 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. |
|
Keeping this PR open — the branch remains cleanly mergeable with |
abhishekverma-ray
left a comment
There was a problem hiding this comment.
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_/_fittedby 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_batchgives the new encoding; serialize()/ pickle after a transform still transforms correctly;- one LabelEncoder
inverse_transformround 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]>
|
Thanks for the review @abhishekverma-ray! Updated in 92f1611:
Verified locally with |

Why are these changes needed?
OrdinalEncoder._get_arrow_arraysandOneHotEncoder._get_arrow_arraysrebuild PyArrow vocabulary arrays on every batch:During
_fit,OrdinalEncoderandOneHotEncoderpopulateself.stats_[f"unique_values({col})"]as a Python{category: index}dict. Because both preprocessors preferBatchFormat.ARROW, every_transform_arrowbatch call invokes_get_unique_value_arrow_arrays(self.stats_, input_col), which re-sorts allVkeys in Python (sorted(stat_value.keys())) and allocates two new PyArrow arrays (pa.array(sorted_keys)andpa.array([stat_value[k] for k in sorted_keys])) inO(V log V)time per batch per column. On 4,096-row string batches withV = 10k–100kcategories, this per-batch dict-to-Arrow conversion accounts for ~70–75% of_transform_arrowruntime (3.5 ms -> 0.8 msatV=10k, 4.1x speedup;62 ms -> 15.5 msatV=100k, 4.0x speedup).LabelEncoder._inverse_transform_pandasrebuilds the inverse label dict on every batch:LabelEncoder._inverse_transform_pandasreconstructs{value: key for key, value in self.stats_[f"unique_values({self._label_column})"].items()}on every batch insidecolumn_label_decoder.Changes
_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 ofself.stats_[f"unique_values({input_col})"]so re-fitting or replacingstats_automatically invalidates the cache.{index: label}dictionary inLabelEncoder._inverse_transform_pandaswith the samestats_identity/length invalidation._arrow_arrays_cacheand_inverse_label_cachein__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.pyby @cem-anyscale (#59810), @xinyuangui2 (#59890, #60790), @abhishekverma-ray (#66088, #66091), and @ayushk7102 (#62618, #62623).Related issue number
N/A
Checks
git commit -s) in this PR.scripts/format.shto lint the changes in this PR.python/ray/data/tests/preprocessors/test_encoder.py).