Repository navigation
[Data] Fix preprocessors that break on missing data - #65272
goutamvenkat-anyscale merged 6 commits into
Conversation
44161d5 to
3b845a4
Compare
f676a8e to
a4a7116
Compare
There was a problem hiding this comment.
Code Review
This pull request ensures that pandas batches handed to user-defined functions are NumPy-backed by default, preventing compatibility issues with Arrow-backed pandas (such as missing operators or pd.NA propagation). It introduces a to_numpy_backed utility and an internal arrow_backed_pandas flag to allow Ray's own preprocessors to opt into Arrow-backed pandas for performance. The review feedback highlights a critical performance optimization in to_numpy_backed to avoid reconstructing DataFrames column-by-column when no Arrow-backed columns are present.
57a1773 to
3835e3c
Compare
Ray 2.56 (ray-project#63017) made `BlockAccessor.to_pandas` hand out Arrow-backed pandas frames, in which a missing value is `pd.NA` rather than `np.nan`. Five preprocessors regressed. Each is fixed locally; batches stay Arrow-backed, so ray-project#63017's memory and speed win is kept. The change swapped a sentinel that silently pretends to be a number for one that refuses to be anything. `np.nan` is a `float`, so it takes part in any float operation and always gives an answer: `np.nan >= 0` is False, `0 + np.nan` is `nan`, and a NumPy array holding it stays `float64`. None of those answers is meaningful for a missing value, but each is usable, and this code had been written to them. `pd.NA` gives none of them, and multi-column `df[cols].to_numpy()` over Arrow-backed columns returns `dtype=object` even with nothing missing, because pandas has no rule for combining Arrow extension types into one NumPy dtype. So each regression fix is the same shape: say out loud what `np.nan` used to say silently. - PowerTransformer: `.fillna(False)` on the sign mask, since `pd.NA >= 0` is `pd.NA` and a three-valued mask cannot index a NumPy array. A missing value takes the negative branch, where the arithmetic leaves it missing -- the same result as before, when `np.nan >= 0` was already False. - Concatenator: stack one column at a time instead of calling `to_numpy` on a multi-column selection. A single Arrow-backed column converts to its natural NumPy dtype. Previously the output tensor column silently became pickled Python objects, with no error raised and no null required to trigger it. - FeatureHasher: map a missing token count to `np.nan`. `0 + pd.NA` is `pd.NA`, which absorbs the accumulator and degrades the output column to `dtype=object`; `np.nan` propagates the same way but stays a float. - Encoder fit path: `_is_null` extended to `pd.NA`/`pd.NaT`, so a null is filtered before `sorted()` instead of raising `TypeError: boolean value of NA is ambiguous`, and the documented "consider imputing missing values first" ValueError is reached again. `Counter.update` guarded for the same reason. - `_is_series_composed_of_lists`: recognise a list column from an Arrow dtype. It gated on `is_object_dtype`, which is False for `list<item: string>[pyarrow]`, so list columns were treated as scalar and sent to `value_counts`, which has no pyarrow kernel for lists. This broke MultiHotEncoder with no nulls at all, and OrdinalEncoder on list columns. MaxAbsScaler is the mirror image: it needed to express something `np.nan` could not express. Fitting an all-null column leaves `stats_` holding None, and `s / None` has no answer for a float column, so it raised TypeError. For an Arrow-backed column None is a valid null scalar of the column's own type, so the division yields nulls -- the right answer, and the one StandardScaler was patched to give in ray-project#51281. An explicit guard mirroring StandardScaler's makes the two paths agree instead of leaving the correct result to depend on a pandas arithmetic rule. No behaviour change on the default path. The survey that found those regressions also found seven preprocessors that were already broken on missing data before ray-project#63017, failing identically on both representations. They are the same situations failing in the same illegible way, so they are fixed to the same rule: propagate the gap, or refuse with an error naming the column. Propagate, because the output can represent "missing" and the work is per-row: - MinMaxScaler, RobustScaler -- an all-null column has no range and no quantiles, so `fit` has no statistic to store. Return nulls, as StandardScaler has for an uncomputable mean or std since ray-project#51281. MinMaxScaler previously reported `'DataFrame' object has no attribute 'name'`: the real failure is `max - min` on two Nones, but `DataFrame.transform` retries a failing per-column function with the whole frame, and the retry dies on `s.name` instead. RobustScaler failed earlier still, in `fit`, unpacking an empty list of quantiles. - Tokenizer, CountVectorizer, HashingVectorizer -- a missing document is not tokenized, and contributes nothing to CountVectorizer's vocabulary. It gets no token list and no count vector, rather than a zero vector that would be indistinguishable from a document containing none of the vocabulary. These three died on a single missing cell in a text column, with `AttributeError: 'NAType' object has no attribute 'split'`. The guard lives at the call site rather than in `simple_split_tokenizer`, because a user-supplied `tokenization_fn` should not have to know about `pd.NA` either. Refuse, because no defensible output exists: - UniformKBinsDiscretizer -- with no observed values there is no range to divide into `bins` intervals. Was `TypeError: unsupported operand type(s) for +: 'NoneType' and 'float'`. - SimpleImputer(strategy="most_frequent") -- nothing to impute from. This message already existed for `strategy="mean"` (f4c4c81) but was unreachable here: the strategy died during `fit` on `most_common(1)[0][0]` with `IndexError: list index out of range`, before the guard that raises it. Tests: `tests/test_preprocessors_arrow_backed.py` covers 19 preprocessors across four input shapes -- no nulls, some nulls, an all-null column, and the same data as a NumPy-backed pandas block -- asserting that output stays numeric rather than `dtype=object`, that a missing input stays missing, and that the two refusals name the column rather than only raising the right exception type. Its `_is_missing` helper also counts `pd.NA`, which is what a missing value looks like when the output column keeps the block in pandas, as a column of Python lists does. The RobustScaler all-null case is worth a note: it was passing locally only because `datasketches` was absent, which skipped the test. It fails without this fix anywhere that optional package is installed, including CI. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Aarrya <[email protected]>
607cf79 to
28f6766
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
Reviewed by Cursor Bugbot for commit 28f6766. Configure here.
| NumPy-backed column would. | ||
| """ | ||
| columns = [df[column].to_numpy(dtype=dtype) for column in self._columns] | ||
| return np.column_stack(columns) |
There was a problem hiding this comment.
Concatenator nulls still yield object arrays
High Severity
_stack_columns calls Series.to_numpy() without na_value=np.nan. For Arrow-backed columns that contain nulls, pandas returns dtype=object with pd.NA rather than widening to a numeric array with np.nan, so the silent non-numeric tensor regression this change aims to fix still happens whenever any concatenated column is missing. The same gap leaves flatten=True and an integer dtype raising on pd.NA.
Reviewed by Cursor Bugbot for commit 28f6766. Configure here.
There was a problem hiding this comment.
import numpy as np, pandas as pd, pyarrow as pa
arrow_int = pd.Series([1, None, 3], dtype=pd.ArrowDtype(pa.int64()))
print(arrow_int.to_numpy(), arrow_int.to_numpy().dtype) # [ 1. nan 3.] float64
arrow_bool = pd.Series([True, None, False], dtype=pd.ArrowDtype(pa.bool_()))
print(arrow_bool.to_numpy(na_value=np.nan).dtype) # object
print(pd.Series([True, None, False], dtype=object).to_numpy().dtype) # object
A single Arrow-backed numeric column with nulls already converts to float64/np.nan, so pd.NA never reaches the tensor — the bug being fixed is df[cols].to_numpy() returning object for a multi-column Arrow selection even with no nulls, which per-column conversion avoids.
The columns that do stay object are bool and string, where na_value=np.nan changes nothing and the behaviour predates Arrow backing (a NumPy-backed bool column with nulls is object too), so that's a separate change needing a per-dtype decision.
- OneHotEncoder and OrdinalEncoder(encode_lists=False): skip nulls when making lists hashable, so a missing row reaches the documented "impute missing values first" ValueError instead of a TypeError buried in a Ray task. - CountVectorizer._fit: accumulate tokens with chain.from_iterable instead of Series.sum(), which reduced with list.__add__ and was quadratic in document count (5.9s vs 12ms at 40k documents). - Move the new test into tests/preprocessors/ so the BUILD glob picks it up; it had no bazel target and was never run by CI. - Restore imputer.py's # noqa (docstyle false positive) and annotate kwargs in the imputer test (pyrefly). Signed-off-by: Aarrya <[email protected]> Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request updates several Ray Data preprocessors (including Concatenator, Discretizer, Encoder, Hasher, Imputer, Scaler, Tokenizer, Transformer, and Vectorizer) to properly handle Arrow-backed pandas DataFrames, which represent missing values with pd.NA and pd.NaT instead of np.nan. It ensures that missing values either propagate correctly or raise clear, documented errors instead of obscure TypeErrors or IndexErrors. A comprehensive test suite is also added to verify these behaviors. The review feedback highlights opportunities to avoid potential ValueError and SettingWithCopyWarning issues in scaler.py by returning a new Series instead of performing in-place assignment, and suggests a performance optimization in utils.py by converting a pandas Series to a NumPy array before zipping.
| if s_min is None or s_max is None: | ||
| s[:] = np.nan | ||
| return s |
There was a problem hiding this comment.
Using in-place assignment s[:] = np.nan on a pandas Series can raise a ValueError: cannot convert float NaN to integer if the Series has a standard NumPy integer dtype (e.g., int64). It can also trigger a SettingWithCopyWarning in pandas.\n\nReturning a new Series constructed with pd.Series(np.nan, index=s.index, dtype=np.float64) is safer, cleaner, and avoids these issues entirely.
if s_min is None or s_max is None:\n return pd.Series(np.nan, index=s.index, dtype=np.float64)| if s_abs_max is None: | ||
| s[:] = np.nan | ||
| return s |
There was a problem hiding this comment.
Using in-place assignment s[:] = np.nan on a pandas Series can raise a ValueError: cannot convert float NaN to integer if the Series has a standard NumPy integer dtype (e.g., int64). It can also trigger a SettingWithCopyWarning in pandas.\n\nReturning a new Series constructed with pd.Series(np.nan, index=s.index, dtype=np.float64) is safer, cleaner, and avoids these issues entirely.
if s_abs_max is None:\n return pd.Series(np.nan, index=s.index, dtype=np.float64)| if s_low_q is None or s_median is None or s_high_q is None: | ||
| s[:] = np.nan | ||
| return s |
There was a problem hiding this comment.
Using in-place assignment s[:] = np.nan on a pandas Series can raise a ValueError: cannot convert float NaN to integer if the Series has a standard NumPy integer dtype (e.g., int64). It can also trigger a SettingWithCopyWarning in pandas.\n\nReturning a new Series constructed with pd.Series(np.nan, index=s.index, dtype=np.float64) is safer, cleaner, and avoids these issues entirely.
if s_low_q is None or s_median is None or s_high_q is None:\n return pd.Series(np.nan, index=s.index, dtype=np.float64)| a list column of numbers with a missing entry, rather than a list of missing | ||
| numbers. | ||
| """ | ||
| return [None if missing else row for row, missing in zip(rows, source.isna())] |
There was a problem hiding this comment.
Iterating over a pandas Series directly in a loop or zip introduces significant overhead because pandas has to perform index alignment and type checking for each element access.\n\nConverting the boolean Series to a raw NumPy array using .to_numpy() avoids this overhead entirely, making the list comprehension significantly faster, especially for larger datasets.
| return [None if missing else row for row, missing in zip(rows, source.isna())] | |
| return [None if missing else row for row, missing in zip(rows, source.isna().to_numpy())] |
zip over `isna().to_numpy()` rather than the Series: same result, ~1.5x faster (1.9x for an Arrow-backed column) on the per-row comprehension, since it skips per-element boxing through the extension array. Signed-off-by: Aarrya <[email protected]> Co-Authored-By: Claude Opus 5 (1M context) <[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. |
| if isinstance(series.dtype, pd.ArrowDtype): | ||
| arrow_type = series.dtype.pyarrow_dtype | ||
| return ( | ||
| pa.types.is_list(arrow_type) | ||
| or pa.types.is_large_list(arrow_type) | ||
| or pa.types.is_fixed_size_list(arrow_type) | ||
| ) |
There was a problem hiding this comment.
Should be able to reuse the function in datatype.py
dt = DataType.from_dtype(series.dtype)
return dt is not None and dt.is_list_type()
There was a problem hiding this comment.
Agreed. Pushing the change.
Reuse `DataType.from_dtype(...).is_list_type()` in `_is_series_composed_of_lists` instead of hand-rolling the pyarrow type predicates. Same result on list/large_list/fixed_size_list, and it also covers list_view and large_list_view (pyarrow 16+), which the hand-rolled check missed. NumPy-backed and tensor dtypes still fall through to the object-dtype check. Signed-off-by: Aarrya <[email protected]> Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…d pandas batches (#66578) (#66617) Cherry-pick of #66578 (master commit 00994a0) onto releases/2.59.0. Conflict resolved: the original commit also extends `python/ray/data/tests/preprocessors/test_preprocessors_arrow_backed.py`, but that file was created on master by #65272 (not on this branch) and its baseline tests assert #65272 behavior the branch doesn't have — so this pick carries the code fix only (`preprocessor.py`, `arrow_block.py`) without the test file. If test coverage on the branch is wanted, #65272 would need to be picked first. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Marwan Sarieddine <[email protected]> Signed-off-by: Aarrya <[email protected]> Signed-off-by: elliot-barn <[email protected]> Co-authored-by: Marwan Sarieddine <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Aarrya <[email protected]>
…d pandas batches (#66578) (#66644) Cherry-pick of #66578 (master commit 00994a0) onto `releases/2.60.0`. Applied cleanly with `git cherry-pick -x`; the diff is identical to the master commit. Unlike the 2.59.0 pick (#66617), this one carries the test file too: `releases/2.60.0` already has #65272, which created `test_preprocessors_arrow_backed.py`. Not a duplicate: no existing PR against `releases/2.60.0` references #66578. Testing: Ray wheel built from the branch-cut commit (838592a) with the branch's `ray/data` and `ray/tests` linked in via `setup-dev.py`, pandas 2.3.3 / pyarrow 23.0.1 / datasketches 5.2.0 (the data CI pins): ``` python -m pytest --pyargs ray.data.tests.preprocessors.test_preprocessors_arrow_backed 137 passed, 3 skipped ``` The 3 skips are by design (a pandas block can't carry a list column). With `preprocessor.py` and `arrow_block.py` reverted to the branch's pre-pick versions (run before `datasketches` was installed), the same file gives 26 failed, 106 passed, 8 skipped, so the tests exercise the fix on this branch. The rest of the preprocessor suite wasn't run locally; relying on branch CI. AI assistance was used to prepare this cherry-pick. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Marwan Sarieddine <[email protected]> Signed-off-by: Aarrya <[email protected]> Signed-off-by: sai.miduthuri <[email protected]> Co-authored-by: Marwan Sarieddine <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Aarrya <[email protected]>
## Description Ray 2.56 (ray-project#63017) made `BlockAccessor.to_pandas` hand out **Arrow-backed** pandas frames — columns typed `double[pyarrow]` rather than `float64`, with a missing value spelled `pd.NA` rather than `np.nan`. Preprocessors receive that frame directly, and five of them broke. The change swapped a sentinel that silently pretends to be a number for one that refuses to be anything. `np.nan` is a `float`, so it joins in any float operation and always produces an answer: `np.nan >= 0` is `False`, `0 + np.nan` is `nan`, and a NumPy array holding it stays `float64`. None of those answers is *meaningful* for a missing value, but each is *usable*, and this code had been written to them. `pd.NA` provides none of them. Separately, and with nothing to do with missing values, `df[["a", "b"]].to_numpy()` over more than one Arrow-backed column returns `dtype=object` even when nothing is missing. This PR fixes those five, plus seven more preprocessors that the same survey found already broken on missing data before ray-project#63017. Every fix is local to `preprocessors/`: **batches stay Arrow-backed**, so ray-project#63017's memory and speed win is kept — nothing is converted back to NumPy-backed pandas. ## Related issues Related to CI-2270. ## Additional information ### What this means for UDFs A user's `map_batches(fn, batch_format="pandas")` UDF receives the same Arrow-backed frame these preprocessors do, and can hit the same problems. Those problems are upstream in Arrow-backed pandas rather than in Ray, so **this PR does not change what a UDF is handed** — reverting the conversion is what would give up ray-project#63017's win. The workarounds are small and local, and are the same ones used below: - A mask is now three-valued: `s >= 0` yields `True`/`False`/`pd.NA`, and a mask containing `pd.NA` cannot index a NumPy array. `(s >= 0).fillna(False)` makes it indexable again without giving the missing row a value. - Convert one column at a time rather than calling `df[cols].to_numpy()` on a multi-column selection, which is what degrades to `dtype=object`. A UDF that needs the old representation can opt out per-job with `DataContext.get_current().enable_arrow_backed_pandas_conversion = False`. That is the same flag used to measure every "pre-2.56" line below, so both behaviours are reachable from one install. ### Regressions from ray-project#63017 All five restore the pre-2.56 result, so nothing new is decided here. ``` PowerTransformer What it does Applies a Yeo-Johnson style power transform with a user-supplied power `p`, using a different formula on either side of zero: a non-negative value becomes `((x + 1)**p - 1) / p`, and a negative one becomes `-((-x + 1)**(2 - p) - 1) / (2 - p)`, with logarithms substituted at `p == 0` and `p == 2` where those would divide by zero. Which formula a row gets is decided by a boolean mask of the non-negative rows, which is then used to index the output array. The case One value in the column is missing. One is enough -- not a degenerate input. Pre-2.56 ok -> the missing row stays missing Post-2.56 IndexError Changed to pre-2.56. ``` ``` Concatenator What it does Packs several numeric columns into one tensor column, a fixed-width vector per row -- typically the last step before features reach a model. The case Two or more numeric columns. Nothing has to be missing: two doubles are enough for the stacked array to come out `dtype=object`. A missing value is only what makes it visible at the Dataset level, since with no nulls Ray rebuilds a numeric tensor from that object array on the way out. Pre-2.56 ok -> ArrowTensorType, dtype=double Post-2.56 dtype=object, silently; ArrowPythonObjectType -- pickled Python objects -- once a value is missing Changed to pre-2.56. ``` ``` FeatureHasher What it does Applies the hashing trick to a table of token counts: each input column is one token, each cell that token's count for that row. It hashes every token name to one of `num_features` buckets and sums the counts of the tokens sharing a bucket, giving a fixed-width vector per row. The case One token count is missing, so one bucket's sum is unknown. Pre-2.56 ok -> dtype=float64, that bucket holds nan Post-2.56 ok -> dtype=object Changed to pre-2.56. ``` ``` OrdinalEncoder / OneHotEncoder / LabelEncoder (the shared fit path) What it does Maps each distinct category to an integer during fit. A null is not a category, so all three refuse to fit a column containing one and tell the user to impute first. The case One label is missing. Pre-2.56 ValueError: Unable to fit column because it contains null values. Consider imputing missing values first. Post-2.56 TypeError: boolean value of NA is ambiguous Refusing is correct and deliberate here; what regressed is which error arrives. Changed to pre-2.56. ``` ``` MultiHotEncoder / OrdinalEncoder on list columns What it does MultiHotEncoder turns a column of lists into a fixed-width count vector, one position per category seen during fit. Whether a column is judged to hold lists is what selects that behaviour over scalar encoding. The case A list column with no missing values anywhere. The one regression that needs no nulls at all -- it broke MultiHotEncoder outright. Pre-2.56 ok Post-2.56 ArrowNotImplementedError Changed to pre-2.56. ``` #### `MaxAbsScaler`, the mirror image The five above lost something when `np.nan` became `pd.NA`. `MaxAbsScaler` gained something, because it needed to express what `np.nan` cannot: a statistic that *does not exist*. ``` MaxAbsScaler What it does Divides a column by the largest absolute value seen during fit, mapping it onto [-1, 1] without shifting zero. The case A column with no observed values at all, so fit has no absolute maximum to store. A single missing value is fine and always was. Pre-2.56 AttributeError: 'DataFrame' object has no attribute 'name' Post-2.56 ok -> nulls Changed to post-2.56, for the NumPy-backed path too: post-2.56 only gets nulls because dividing an Arrow-backed column by None happens to yield nulls, so without an explicit guard this still fails under `enable_arrow_backed_pandas_conversion = False`. ``` ### Already broken before ray-project#63017 Seven cases, none a regression: each fails identically on Arrow-backed and NumPy-backed blocks. Four need a column with **no observed values at all**; the three text ones need only **a single missing cell**, which is why they are the ones most likely to be hit in production. These are the cases where we pick neither the pre- nor the post-2.56 result, so each says why. ``` MinMaxScaler What it does Rescales a column onto [0, 1] using a min and max computed during fit. The case A column with no observed values, so fit stores None for both the min and the max and there is no range to scale into. Pre-2.56 AttributeError: 'DataFrame' object has no attribute 'name' Post-2.56 AttributeError: 'DataFrame' object has no attribute 'name' The error names the wrong thing entirely. `max - min` on two Nones raises `TypeError`, but the per-column function is applied by pandas' `DataFrame.transform`, which answers a per-column failure by retrying with the whole frame -- and the retry dies first, on `s.name`. So the user hears about a missing `DataFrame` attribute, and never about the column or the missing data. What we chose Propagate: every row of the output column is null. Scaling a missing value gives a missing value, and a column with no observed values has nothing that is not missing. Refusing would be wrong because an all-null column is ordinary at scale -- one partition of a large table, or a feature populated only for some records -- and failing the whole job is worse than returning nulls the caller can see. The *other* degenerate case is already handled a few lines away, a constant column, whose near-zero range is treated as 1. ``` ``` RobustScaler What it does Centres a column on its median and scales it by the distance between two quantiles, all three taken from an approximate-quantile sketch built during fit. The case A column with no observed values. The sketch is empty, so fit gets an empty list where it expects three quantiles. Pre-2.56 ValueError: not enough values to unpack (expected 3, got 0) Post-2.56 ValueError: not enough values to unpack (expected 3, got 0) What we chose Propagate: fit records "no quantile" for each of the three statistics and every row of the output column is null. A column with no observed values has nothing to centre or scale by, and an all-null column is ordinary at scale -- failing the whole job over one is worse than returning nulls. Fit is also where it has to be fixed, since that is where it fails; guarding the transform alone would not have been enough. ``` ``` UniformKBinsDiscretizer What it does Buckets a numeric column into N equal-width bins, deriving the bin edges from the column's min and max during fit. The case A column with no observed values, so the min and max are None and computing the bin edges does arithmetic on None. Pre-2.56 TypeError: unsupported operand type(s) for +: 'NoneType' and 'float' Post-2.56 TypeError: unsupported operand type(s) for +: 'NoneType' and 'float' What we chose Refuse, naming the column: `Column x has no values to bin. Check the data used to fit the discretizer.` The one case here that cannot propagate -- with no range there are no bins, so the fitted preprocessor is meaningless rather than just this column's output. `CustomKBinsDiscretizer` is unaffected, since its edges come from the user. ``` ``` SimpleImputer(strategy="most_frequent") What it does Fills a column's missing values with its commonest value, found during fit by counting values across the dataset. The case A column with no observed values, so the counter is empty and fit asks it for its most common entry. Pre-2.56 IndexError: list index out of range Post-2.56 IndexError: list index out of range What we chose Refuse with the error this file already raises whenever the fitted fill value is missing: `Column x has no fill value. Check the data used to fit the SimpleImputer.` There is nothing to impute from, and it is the same preprocessor in the same impossible situation, so it should be the same error. The guard is strategy-agnostic, but only `"mean"` could reach it -- an all-null column gives it a fill value of None and fit still succeeds, whereas `"most_frequent"` crashed during fit and never got there. Comments pointing this out **That error already existed in this file and was simply unreachable for this strategy.** `most_frequent` crashed during fit, before the transform guard that raises it could run. The guard came from f4c4c81, whose description names this exact class of bug -- "the preprocessor fails with an unintuitive error" -- so the fix was written and this strategy slipped past it. All it needed was for fit to report "no value" instead of indexing an empty list. ``` ``` Tokenizer What it does Replaces each string with a list of tokens; the default tokenizer splits on spaces. Row-wise -- it computes nothing during fit. The case One row's text is missing, and the tokenizer is handed it. Pre-2.56 AttributeError: 'NoneType' object has no attribute 'split' Post-2.56 AttributeError: 'NAType' object has no attribute 'split' The same failure both times, only the missing-value object is named differently. One empty cell in a text column kills the whole job. What we chose Propagate: a missing document is never passed to the tokenizer and its output stays null. Null rather than an empty list, so "no text" stays distinguishable from "text containing no words" -- a caller can always fill the nulls, but cannot recover the distinction once it is gone. The guard sits where the tokenizer is called rather than inside the default tokenizer, because the tokenization function can be supplied by the user, and a user's function should not have to know about `pd.NA` either. It is `Series.map(fn, na_action="ignore")`, so a custom tokenizer is covered too. ``` ``` CountVectorizer What it does Turns a text column into a per-token count vector, over a vocabulary of the most frequent tokens collected during fit. The case One row's text is missing. Fit tokenizes every row to count tokens and is handed the missing one, so this fails during fit rather than transform. Pre-2.56 AttributeError: 'NoneType' object has no attribute 'split' Post-2.56 AttributeError: 'NAType' object has no attribute 'split' What we chose Propagate: a missing document contributes no tokens to the vocabulary and its count vector is null. Skipping it corrupts nothing -- the vocabulary built from the remaining documents is exactly the vocabulary of the text that exists. ``` ``` HashingVectorizer What it does Turns a text column into a fixed-width count vector by hashing each token into one of `num_features` buckets. It learns no vocabulary, so it needs no fit. The case One row's text is missing, and tokenizing it is what fails. Pre-2.56 AttributeError: 'NoneType' object has no attribute 'split' Post-2.56 AttributeError: 'NAType' object has no attribute 'split' What we chose Propagate: a missing document gets a null count vector rather than a zero vector, so it stays distinguishable from a document whose tokens all hash elsewhere. The least ambiguous of the three text cases: with no fitted state at all, a missing row cannot affect any other row's output. ``` ### Tests New file `python/ray/data/tests/test_preprocessors_arrow_backed.py` runs 19 preprocessors over four input shapes — no nulls, one null per column, a column that is entirely null, and the same data as a NumPy-backed pandas block, so every case is checked against both representations rather than only the new one. It asserts that output stays numeric rather than `dtype=object`, that a missing input stays missing, and that the two refusals name the column. 91 passed, 1 skipped (a pandas block cannot carry a Python-list column, which is a block limitation rather than anything these tests measure). Existing `tests/preprocessors/`: 249 passed, 2 pre-existing skips. Run against the pre-fix code the new file fails 18 of its cases, so it measures the fixes rather than describing them. One of those 18 was already red rather than xfailed: the all-null `RobustScaler` case was passing locally only because `RobustScaler`'s fit needs the optional `datasketches` package, whose absence skipped the test. It fails without this PR anywhere that package is installed, including CI. --------- Signed-off-by: Aarrya <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…th existing category values (#67467) ## Why are these changes needed? In `ray.data.preprocessors.SimpleImputer._transform_pandas`, two bugs caused imputation on `pd.Categorical` columns to raise `TypeError` or `ValueError`: 1. **Append mode (`output_columns` specified, `output_column != column`) overwrote the newly added category**: Previously, `df[output_column] = df[column].cat.add_categories([value])` was executed *before* `df[output_column] = df[column].copy(deep=True)`. Because `df[column]` still held the original categories without `value`, copying `df[column]` into `df[output_column]` immediately discarded the added category, causing `df.fillna({output_column: value}, inplace=True)` to fail with: `TypeError: Cannot setitem on a Categorical with a new category (..., set the categories first)` 2. **Imputing an existing category value (`strategy="most_frequent"` or `strategy="constant"` where `fill_value` is already in `cat.categories`) crashed**: Calling `cat.add_categories([value])` unconditionally without checking `value not in df[output_column].cat.categories` raised: `ValueError: new categories must not include old categories: {...}` In addition, because `df[column].values` on a `pd.Categorical` column is a `pandas.Categorical` ExtensionArray rather than an `np.ndarray`, the writeable-copy guard also checks `is_categorical_dtype(df.dtypes[column]) and not df[column].values.codes.flags.writeable` so in-place `fillna` does not fail on zero-copy / read-only batches when `add_categories` is skipped. ### Changes - Copy `df[column]` into `df[output_column]` first when `output_column != column` or the backing array / categorical codes buffer is non-writeable (`not df[column].values.codes.flags.writeable`). - Guard `df[output_column].cat.add_categories([value])` with `value not in df[output_column].cat.categories`. - Add unit tests in `python/ray/data/tests/preprocessors/test_imputer.py` covering categorical columns in append mode, `strategy="constant"` with an existing category on read-only categorical codes, and `strategy="most_frequent"` on categorical columns. ### Duplicate-work & testing notes - Searched open and closed issues/PRs in `ray-project/ray` for `SimpleImputer` and `add_categories`; no existing issue or PR covers these two categorical bugs. - Tested locally with `pytest python/ray/data/tests/preprocessors/test_imputer.py -k "test_imputer_categorical_append_and_existing_category or test_imputer_all_nan_raise_error or test_imputer_constant_categorical"` (`3 passed`). - AI assistance was used while preparing and verifying this PR. ### Acknowledgments Credit to @abhishekverma-ray (#66091, #66088), @AarryaSaraf (#65272), @rayhhome (#61028), and @cem-anyscale (#58321) for their foundational work on `SimpleImputer` and `output_columns` support in `ray.data.preprocessors`, and to @gemini-code-assist[bot] and @cursor[bot] for catching the `Categorical.codes.flags.writeable` check. ## Checks - [x] I've signed off every commit(by making the commit message contain `Signed-off-by: ...`) - [x] I've run `pytest python/ray/data/tests/preprocessors/test_imputer.py` locally and verified all tests pass. --------- Signed-off-by: Parth Vadera <[email protected]> Co-authored-by: Copilot <[email protected]>
… Concatenator, and PowerTransformer (#67483) ## Why are these changes needed? This PR fixes silent `NaN` corruption on non-default `pd.DataFrame` indices in `Concatenator` and `FeatureHasher`, and exceptions on zero-row batches in `FeatureHasher` and `PowerTransformer`: 1. **Preserve `df.index` in `Concatenator._transform_pandas` and `FeatureHasher._transform_pandas` (`TestConcatenator.test_non_default_index`, `test_feature_hasher`):** Both preprocessors previously assigned `df.loc[:, output_col] = pd.Series(list(concatenated))` without `index=df.index`. When `transform_batch` is called on a sliced, filtered, or custom-indexed `pd.DataFrame` whose index is not `RangeIndex(0, len(df))` (e.g., `index=[10, 20]`), pandas aligns the newly created `Series` index (`0..n-1`) against `df.index` and silently replaces non-overlapping index positions with `NaN`. Passing `index=df.index` preserves row alignment. 2. **Handle zero-row batches and hoist column-name hashing in `FeatureHasher._transform_pandas` (`test_feature_hasher`):** - On an empty `pd.DataFrame` (`len(df) == 0`), `df.loc[:, self._columns].apply(row_feature_hasher, axis=1, result_type="expand")` returns a 0-row DataFrame with `self._columns` rather than `hash_0 .. hash_{num_features - 1}`, causing `feature_columns[hash_columns]` to raise `KeyError`. Returning an empty `object`-dtype `Series` indexed by `df.index` when `df.empty` avoids the crash. - Precomputes `simple_hash(column, self._num_features)` once per column per batch rather than recomputing the SHA-256 column-name hash inside `row_feature_hasher` on every row. 3. **Return `pd.Series(result, index=s.index)` in `PowerTransformer._transform_pandas` (`yeo-johnson`, `test_power_transformer_empty_batch`):** Unlike the `box-cox` branch (which returns a `pd.Series`), the `yeo-johnson` branch returned a raw `np.ndarray`. On an empty DataFrame (`len(df) == 0`), `pandas.DataFrame.transform` treats a non-`Series` return value in `apply_empty_result` as a scalar reduction and raises `ValueError: Transform function failed`. Returning `pd.Series(result, index=s.index)` makes `yeo-johnson` consistent with `box-cox` on empty batches. ### Related work & acknowledgements - Builds on the preprocessor null-propagation and batch-handling hardening in #65272 by @AarryaSaraf and `FeatureHasher` append-mode support in #50632 by @martinbomio. ## Related issue number N/A ## Checks - [x] I've signed off every commit(by using the -s flag, i.e., `git commit -s`) in this PR. - [x] I've run `scripts/format.sh` to lint the changes in this PR. - [x] I've included any doc changes needed for https://docs.ray.io/en/master/. - [ ] I've added any new APIs to the API reference. For example, if I added a method in Python, I've added it to `doc/source/tune/api/` under the corresponding `.rst` file. - [x] I've made sure the tests are passing. Note that there might be a few flaky tests, see the recent failures at https://flakey-tests.ray.io/ - Testing Strategy - [x] Unit tests (`python/ray/data/tests/preprocessors/test_concatenator.py`, `python/ray/data/tests/preprocessors/test_hasher.py`, `python/ray/data/tests/preprocessors/test_transformer.py`) - [ ] Release tests - [ ] This PR is not tested :( --------- Signed-off-by: Parth Vadera <[email protected]> Co-authored-by: Copilot <[email protected]>


Description
Ray 2.56 (#63017) made
BlockAccessor.to_pandashand out Arrow-backed pandasframes — columns typed
double[pyarrow]rather thanfloat64, with a missing valuespelled
pd.NArather thannp.nan. Preprocessors receive that frame directly, andfive of them broke.
The change swapped a sentinel that silently pretends to be a number for one that
refuses to be anything.
np.nanis afloat, so it joins in any float operation andalways produces an answer:
np.nan >= 0isFalse,0 + np.nanisnan, and a NumPyarray holding it stays
float64. None of those answers is meaningful for a missingvalue, but each is usable, and this code had been written to them.
pd.NAprovidesnone of them. Separately, and with nothing to do with missing values,
df[["a", "b"]].to_numpy()over more than one Arrow-backed column returnsdtype=objecteven when nothing is missing.This PR fixes those five, plus seven more preprocessors that the same survey found
already broken on missing data before #63017. Every fix is local to
preprocessors/:batches stay Arrow-backed, so #63017's memory and speed win is kept — nothing is
converted back to NumPy-backed pandas.
Related issues
Related to CI-2270.
Additional information
What this means for UDFs
A user's
map_batches(fn, batch_format="pandas")UDF receives the same Arrow-backedframe these preprocessors do, and can hit the same problems. Those problems are
upstream in Arrow-backed pandas rather than in Ray, so this PR does not change what a
UDF is handed — reverting the conversion is what would give up #63017's win. The
workarounds are small and local, and are the same ones used below:
s >= 0yieldsTrue/False/pd.NA, and a maskcontaining
pd.NAcannot index a NumPy array.(s >= 0).fillna(False)makes itindexable again without giving the missing row a value.
df[cols].to_numpy()on amulti-column selection, which is what degrades to
dtype=object.A UDF that needs the old representation can opt out per-job with
DataContext.get_current().enable_arrow_backed_pandas_conversion = False. That is thesame flag used to measure every "pre-2.56" line below, so both behaviours are reachable
from one install.
Regressions from #63017
All five restore the pre-2.56 result, so nothing new is decided here.
MaxAbsScaler, the mirror imageThe five above lost something when
np.nanbecamepd.NA.MaxAbsScalergainedsomething, because it needed to express what
np.nancannot: a statistic that doesnot exist.
Already broken before #63017
Seven cases, none a regression: each fails identically on Arrow-backed and NumPy-backed
blocks. Four need a column with no observed values at all; the three text ones need
only a single missing cell, which is why they are the ones most likely to be hit in
production. These are the cases where we pick neither the pre- nor the post-2.56
result, so each says why.
Tests
New file
python/ray/data/tests/test_preprocessors_arrow_backed.pyruns 19preprocessors over four input shapes — no nulls, one null per column, a column that is
entirely null, and the same data as a NumPy-backed pandas block, so every case is
checked against both representations rather than only the new one. It asserts that
output stays numeric rather than
dtype=object, that a missing input stays missing, andthat the two refusals name the column. 91 passed, 1 skipped (a pandas block cannot
carry a Python-list column, which is a block limitation rather than anything these
tests measure). Existing
tests/preprocessors/: 249 passed, 2 pre-existing skips.Run against the pre-fix code the new file fails 18 of its cases, so it measures the
fixes rather than describing them. One of those 18 was already red rather than xfailed:
the all-null
RobustScalercase was passing locally only becauseRobustScaler's fitneeds the optional
datasketchespackage, whose absence skipped the test. It failswithout this PR anywhere that package is installed, including CI.