Skip to content

[Data][PreProc][3/4] Deferred Chain fit with batched aggregations (off by default) - #66091

Merged
goutamvenkat-anyscale merged 12 commits into
ray-project:masterfrom
abhishekverma-ray:preproc-3-deferred-chain-fit
Oct 23, 2026
Merged

goutamvenkat-anyscale merged 12 commits into
ray-project:masterfrom
abhishekverma-ray:preproc-3-deferred-chain-fit

Conversation

@abhishekverma-ray

@abhishekverma-ray abhishekverma-ray commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Why are these changes needed?

Chain.fit() runs one full dataset scan per fittable member — and because Ray
Datasets are lazy, each scan also re-executes the upstream read/transform
pipeline. A Chain(SimpleImputer, StandardScaler, OrdinalEncoder) reads the
data three times to fit.

Every fit statistic is the answer to an aggregation query (mean/std, unique
values, value counts), and members that touch disjoint columns are
independent. This PR adds an opt-in fast path that batches those queries:

  • With DataContext.enable_aggregation_based_preprocessors set (env:
    RAY_DATA_ENABLE_AGGREGATION_BASED_PREPROCESSORS, default off),
    Chain.fit() only registers each member's aggregations on its stat
    computation plan and returns.
  • The first transform() schedules the scans (new preprocessors/dag.py,
    two pure functions). _fit_order picks a fit-time order in which members
    touching disjoint columns can share a scan; _fit_levels then gives each
    member a level (a layered topological sort: a member depends on an earlier
    one iff it reads a column the earlier one writes). Each level's
    aggregations run as one Dataset.aggregate() call; results are routed
    into each member's stats_ by aggregator alias; fitted members then
    transform the (lazy) fit dataset so the next level aggregates over
    transformed data. Cost: max(levels) + 1 scans instead of one per member —
    a chain of independent members fits in a single scan.
  • Statistics are computed over the dataset passed to fit() (stashed on
    the chain), never over the dataset being transformed, so the fitted values
    are identical to sequential fitting even when a different dataset is
    transformed first.

The user-visible behavioral change (why this is behind a default-off
flag): with the flag on, Chain.fit() returns with member stats_ empty;
they materialize at the first transform(), transform_batch(), or
serialization. An RFC issue for this semantic is open at #66090 (#66090).

Safety properties (all in this PR, with tests — the flag isn't safe without
them):

  1. Opt-in per class. A new _supports_deferred_fit marker is set only on
    preprocessors whose _fit purely registers plan aggregators
    (StandardScaler, SimpleImputer, and the five encoders as of the previous
    PR). A chain containing any unmarked fittable member — third-party
    subclasses, discretizers, CountVectorizer — keeps today's sequential eager
    fit for the whole chain.
  2. Serial fallback (with a warning) at materialization time if a member
    registered a custom callable stat.
  3. Idempotence: repeated transform() never re-runs aggregations.
  4. Serialization-safe: serialize() and plain pickling of a
    fitted-but-never-transformed chain materialize the stats first, in
    dependency order; the fit dataset itself is never pickled.
  5. Non-fittable members (e.g. Concatenator) take part in scheduling with
    their read/write columns, so a member reading a non-fittable's output only
    aggregates after that transform is applied.
  6. Nested chains defer recursively and fit on the data flowing into their
    chain position.
  7. Two members needing the same aggregation alias in one level run in
    separate query batches instead of colliding on a result column.
  8. Undeclared members are barriers. A member that doesn't declare both
    its input and output columns (the default for user-defined
    preprocessors) is treated as reading and writing every column: later
    members compute statistics only after its transform is applied.
  9. Transform order. Transforms on the fit dataset are applied in fit
    order, stopping at the first member that hasn't fitted yet, and a member
    computes statistics only once every member it depends on (and every
    member before those) has been transformed.
  10. Partly pre-filled stats. Every registered aggregation runs even if
    stats_ is already partly filled (e.g. Categorizer with dtypes given
    for some columns).
  11. Fit dataset released. The dataset passed to fit() is released once
    statistics are computed.
  12. Safe fit-time reordering. Only members that touch disjoint columns
    are fitted out of chain order. Members that share any column (including
    two readers, since Concatenator drops its inputs) and members without
    declared columns keep their chain order. The stored chain and the
    transform() order are unchanged.

Also extracts the aggregate-execution half of StatComputationPlan.compute
into a shared execute_aggregate_specs helper (no behavior change) and gives
Chain get_input_columns/get_output_columns (inputs exclude columns
produced by an earlier member; both lists are de-duplicated in order).

With the flag off (the default), behavior is unchanged; an explicit test
asserts the eager path.

The level-based scheduler (_fit_levels / _fit_order) was contributed by
@goutamvenkat-anyscale during review.

Related issue number

RFC: # 66090. Not a duplicate: searched open PRs/issues for chain
fit / preprocessor aggregation work; no overlap found.

Depends on the encoder-aggregation PR (stacked; will rebase once it lands).

Checks

  • I've signed off every commit (DCO).
  • I've run pre-commit hooks — all hooks pass.
  • Testing (macOS / Python 3.12, source build):
    • pytest python/ray/data/tests/preprocessors/test_chain.py — 35 passed
      (deferral semantics, eager-vs-deferred stats equality, one-query batching
      of independent members, one-scan-per-level, fit levels, fit order and the
      measured scan reduction, no re-aggregation on repeated transform,
      fit-dataset semantics, non-fittable ordering, unmarked-member fallback,
      callable-stat serial fallback, alias collision, nested chain,
      serialization, transform_batch, flag-off eager path, undeclared and
      partially declared member barriers (in levels and in fit order), members
      that skip Preprocessor.__init__, transform ordering, partly pre-filled
      stats, fit-dataset release, Chain input/output columns).
    • pytest python/ray/data/tests/preprocessors/ --ignore=.../test_torch.py
      (torch not installed) — 441 passed, 5 skipped, 0 failed (clean master at
      the same base: 392 passed).
    • pytest python/ray/data/tests/test_aggregations.py — 62 passed.
    • Env matches CI pins (pandas 2.3.3, pyarrow 23.0.1, cloudpickle 3.1.1,
      pytest 7.4.4).
    • Each safety rule was checked by removing it and confirming a test fails.
      A brute-force check of the scheduler over 200k random chains found no case
      where a member fits before the data it needs is ready.

AI assistance was used to draft this change (Claude Code); every line has been
reviewed by the submitter.

🤖 Generated with Claude Code

@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 Sep 25, 2026
@abhishekverma-ray
abhishekverma-ray force-pushed the preproc-3-deferred-chain-fit branch from a9ad7d1 to bf8a86e Compare September 29, 2026 06:41
@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 Sep 29, 2026
@abhishekverma-ray
abhishekverma-ray force-pushed the preproc-3-deferred-chain-fit branch 2 times, most recently from 7230ebd to 2e8318f Compare September 30, 2026 16:10
elliot-barn pushed a commit that referenced this pull request Sep 30, 2026
)

## What broke

Calling a preprocessor's `transform_batch` inside a
`map_batches(batch_format="pandas")`
UDF fails on Ray >= 2.56. Three shapes, reported by a user upgrading
from 2.55:

```python
ds = ray.data.from_items([{"n": 1}, {"n": 2}, {"n": 3}, {"n": 4}])
scaler = StandardScaler(columns=["n"]).fit(ds)
ds.map_batches(lambda b: scaler.transform_batch(b), batch_format="pandas").take_all()
```

| input | error |
|---|---|
| int column, `StandardScaler` | `ArrowInvalid: Float value -1.341641
was truncated converting to int64` |
| string column, `OrdinalEncoder` / `OneHotEncoder` | `ValueError:
ArrowStringArray requires a PyArrow (chunked) array of large_string
type` |
| a list column merely *present* in the batch | `TypeError: data type
'list<item: string>[pyarrow]' not understood` |

The third needs no list-typed input to the preprocessor — a `tags`
column sitting
unused in the batch is enough while a float column is scaled.

## Why

`_transform_batch` converted the whole batch with
`pa.Table.from_pandas`, which records
the input dtypes in the table's pandas schema metadata, ran
`_transform_arrow`, and
converted back with `to_pandas`. The transform changes column types —
int64 to double
for a scaler, string to int64 for an ordinal encoding — but the metadata
still described
the input, so the conversion back cast the results to their
pre-transform dtypes.

That round trip landed in 2.54 (#59810). 2.56 (#63017) made pandas
batches Arrow-backed,
which is what made those cast-backs fail. So this is a latent bug that
2.56 exposed
rather than one 2.56 introduced: the same call already failed on 2.55
when handed an
Arrow-backed frame directly.

## The fix

Stop round-tripping the batch. Only the columns the preprocessor reads
(`get_input_columns`) cross into Arrow, without the metadata, and only
the ones it writes
(`get_output_columns`) come back. The result is a shallow copy of the
caller's frame with
those columns replaced, so untouched columns, the index, the axis names
and `attrs` never
leave pandas — there is nothing to rebuild.

- A written column that keeps its Arrow type keeps the dtype of the
column it replaces
  (a scaled `Float64` stays `Float64`).
- Otherwise it keeps that column's backing. An Arrow-backed column stays
Arrow-backed
whatever `enable_arrow_backed_pandas_conversion` says — the flag governs
how Ray
converts its own blocks, not the caller's columns — except for the types
Ray never maps
to an Arrow-backed dtype (extension, dictionary, null), which go through
its block
conversion as before. A NumPy-backed column converts plainly, and a
newly created column
  follows the frame.
- That Arrow-to-pandas type mapping moves unchanged from a closure in
`ArrowBlockAccessor.to_pandas` to module level in `arrow_block.py`, so
both paths share
  one rule.
- A preprocessor that declares no columns falls back to sending the
whole frame.

Writing columns back by position needs `_transform_arrow` to return the
rows it was
given, in order. A changed row count now raises a `ValueError`, and the
`_transform_arrow`
docstring states the contract. All three built-in `_transform_arrow`
implementations are
column transforms and satisfy it.

## Behaviour changes

Both come from untouched columns no longer being re-inferred from Arrow:

- An object column of numbers stays `object`; it used to come back
`int64` / `float64`.
- Integer column labels stay integers; they used to be turned into
strings.

And one for implementers: `_transform_arrow` on a pandas batch now
receives only the
declared input columns, and must not change the rows. The previous code
tolerated a
filtering transform by carrying the index through as a column; it now
raises instead.

## Not a fix for

`enable_arrow_backed_pandas_conversion=False` mitigates this only for
Arrow-block sources.
A pandas block built from an already-Arrow-backed frame — what
`pd.read_parquet(..., dtype_backend="pyarrow")` returns — never
undergoes an
Arrow-to-pandas conversion, so the flag does not reach it; this change
fixes that path.

Two related gaps are left for follow-ups rather than widening this PR:

- `Preprocessor.transform(ds)` has the same stale-metadata defect for a
dataset built from
an Arrow-backed pandas frame with the flag set to `False` (it works with
the default).
- `transform_batch(pa.Table)` returns a table that still carries the
caller's pandas
metadata, so calling `.to_pandas()` on the result can fail the same way.

## Not a duplicate

No open PR touches `_transform_batch` or this pandas/Arrow round trip.
The open
preprocessor work (#66088, #66091) is about how preprocessors are
*fitted* and does not
change the transform path; #60533 adds a `drop` option to the one-hot
encoders in
`encoder.py`. The other open Arrow/pandas PRs are elsewhere: #65539 is
schema
unification for empty datasets, #63938 preserves `CategoricalDtype` in
`Schema.types`.

No open issue covers it either. #64765, the umbrella 2.56 `to_pandas`
regression, is
closed, fixed by #64768 — which added the
`enable_arrow_backed_pandas_conversion`
opt-out and left this round trip untouched.

## Testing

35 `transform_batch` cases added to

`python/ray/data/tests/preprocessors/test_preprocessors_arrow_backed.py`:

- `test_transform_batch_inside_a_pandas_udf` — the three reported
preprocessors through a
  pandas UDF, parametrized over `enable_arrow_backed_pandas_conversion`.
- `test_transform_batch_on_an_arrow_backed_pandas_block` — the shape the
flag does not cover.
- `test_transform_batch_passes_through_an_untouched_list_column` — the
list-column case.
- `test_transform_batch_matches_the_input_backing` /
`..._decides_the_backing_per_column`
— NumPy in gives NumPy out, Arrow in gives Arrow out, and a mixed frame
keeps both.
- `test_transform_batch_keeps_arrow_backing_with_the_flag_off` — the
same holds for all
three preprocessors with `enable_arrow_backed_pandas_conversion=False`.
- `test_transform_batch_keeps_pass_through_extension_dtypes` — nullable
`Int64`, `boolean`
  and `string` columns come back intact, including a value past 2**53.
- `test_transform_batch_leaves_untouched_columns_exactly_as_they_were` —
object columns of
  numbers, a categorical over pandas strings, Python lists.
- `test_transform_batch_preserves_the_index` — named, `MultiIndex` and
tz-aware
  `DatetimeIndex` on both backings, plus the columns axis name.
- `test_transform_batch_keeps_integer_column_labels`,
`..._does_not_modify_the_callers_frame`,
`..._rejects_a_transform_that_changes_the_row_count`,
  `..._on_an_empty_batch`.

The cases assert on values rather than on "did not raise": where the
stale metadata
permitted the cast, the result was silently wrong rather than an error —
an ordinal
encoding coming back as the strings `"0"`, `"1"`, `"2"`.

Against the unmodified source, 21 of the 35 fail:

- 15 are the reported crash on Arrow-backed input.
- 5 are the behaviour changes above: master re-typed untouched object
and categorical
  columns and stringified integer labels.
- 1 is the new contract: master tolerated a filtering
`_transform_arrow`; this raises.

The other 14 pass on master too and are controls — the NumPy-backed
halves, the empty
batch, and the pass-through dtype cases, which guard against a
regression a naive fix
would introduce.

```
$ PYTHONPATH=python/ray/data/tests python -m pytest -q \
    python/ray/data/tests/preprocessors/ --ignore=.../test_torch.py
381 passed, 5 skipped

$ PYTHONPATH=python/ray/data/tests python -m pytest -q python/ray/data/tests/test_arrow_block.py
30 passed
```

The three reported repros were also run end to end through `map_batches`
in Ray workers.
`test_torch.py` is excluded because `torch` is not installed in this
environment; it is
untouched by this change. Pre-commit passes on all three changed files.

Only the declared columns are converted, so wide frames stop paying for
every column:
`StandardScaler(columns=["n"]).transform_batch` on a 1000-column ×
2k-row NumPy frame
goes from ~27 ms to under 1 ms.

AI assistance was used for this change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Signed-off-by: Aarrya <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Aarrya <[email protected]>
@abhishekverma-ray
abhishekverma-ray force-pushed the preproc-3-deferred-chain-fit branch from 2e8318f to ea6281f Compare October 5, 2026 06:48
abhishekverma-ray and others added 2 commits October 5, 2026 14:51
Replaces the driver-side counter merge in preprocessor fitting with
distributed aggregations:

- OrdinalEncoder, OneHotEncoder, MultiHotEncoder, LabelEncoder and
  Categorizer now register Unique (or TopKUnique when max_categories is
  set) aggregators on the stat computation plan instead of the
  compute_unique_value_indices callable stat. That callable ran a
  map_batches over the dataset and then merged per-block counters in a
  loop on the driver - a scalability bottleneck.
- SimpleImputer(strategy="most_frequent") likewise moves from
  _get_most_frequent_values to the existing ValueCounter aggregation
  plus an argmax post-processing step that skips nulls (an Arrow-backed
  column reports nulls as value_counts entries) and breaks frequency
  ties deterministically by picking the smallest value.

Behavior is unchanged: stats_ keys, null-handling errors, list-column
encoding, and global (cross-partition) top-k semantics for
max_categories are all preserved, and each fit is now a single
Dataset.aggregate() query per preprocessor. The legacy helpers
compute_unique_value_indices and _get_most_frequent_values are kept for
backwards compatibility.

Note: fitting an encoder with encode_lists=False on a list-typed Arrow
column now goes through Unique, which uses polars for list-column
uniqueness (same as any Unique aggregation on list columns today).

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
…view feedback

- Use TopKUnique(k=1, ignore_nulls=True) for SimpleImputer(strategy=
  "most_frequent") instead of ValueCounter plus a driver-side argmax helper.
  It yields the same result (most frequent non-null value, ties broken by the
  smallest value, no value for an all-null column) with the vectorized
  column-wise merge, and removes the null-filtering helper that review flagged
  for missing pd.NA and numpy float NaN sentinels.
- Add tests that null sentinels (None, NaN, pd.NA, float32 NaN) are never the
  most frequent value even when they outnumber every real value, and that the
  value is chosen from counts summed across blocks.
- Add a regression test that whole-list categories (OrdinalEncoder with
  encode_lists=False, OneHotEncoder) stay whole lists when merged from several
  partial aggregates.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
@abhishekverma-ray
abhishekverma-ray force-pushed the preproc-3-deferred-chain-fit branch from ea6281f to 8bb2247 Compare October 5, 2026 09:28
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…-project#66578)

## What broke

Calling a preprocessor's `transform_batch` inside a
`map_batches(batch_format="pandas")`
UDF fails on Ray >= 2.56. Three shapes, reported by a user upgrading
from 2.55:

```python
ds = ray.data.from_items([{"n": 1}, {"n": 2}, {"n": 3}, {"n": 4}])
scaler = StandardScaler(columns=["n"]).fit(ds)
ds.map_batches(lambda b: scaler.transform_batch(b), batch_format="pandas").take_all()
```

| input | error |
|---|---|
| int column, `StandardScaler` | `ArrowInvalid: Float value -1.341641
was truncated converting to int64` |
| string column, `OrdinalEncoder` / `OneHotEncoder` | `ValueError:
ArrowStringArray requires a PyArrow (chunked) array of large_string
type` |
| a list column merely *present* in the batch | `TypeError: data type
'list<item: string>[pyarrow]' not understood` |

The third needs no list-typed input to the preprocessor — a `tags`
column sitting
unused in the batch is enough while a float column is scaled.

## Why

`_transform_batch` converted the whole batch with
`pa.Table.from_pandas`, which records
the input dtypes in the table's pandas schema metadata, ran
`_transform_arrow`, and
converted back with `to_pandas`. The transform changes column types —
int64 to double
for a scaler, string to int64 for an ordinal encoding — but the metadata
still described
the input, so the conversion back cast the results to their
pre-transform dtypes.

That round trip landed in 2.54 (ray-project#59810). 2.56 (ray-project#63017) made pandas
batches Arrow-backed,
which is what made those cast-backs fail. So this is a latent bug that
2.56 exposed
rather than one 2.56 introduced: the same call already failed on 2.55
when handed an
Arrow-backed frame directly.

## The fix

Stop round-tripping the batch. Only the columns the preprocessor reads
(`get_input_columns`) cross into Arrow, without the metadata, and only
the ones it writes
(`get_output_columns`) come back. The result is a shallow copy of the
caller's frame with
those columns replaced, so untouched columns, the index, the axis names
and `attrs` never
leave pandas — there is nothing to rebuild.

- A written column that keeps its Arrow type keeps the dtype of the
column it replaces
  (a scaled `Float64` stays `Float64`).
- Otherwise it keeps that column's backing. An Arrow-backed column stays
Arrow-backed
whatever `enable_arrow_backed_pandas_conversion` says — the flag governs
how Ray
converts its own blocks, not the caller's columns — except for the types
Ray never maps
to an Arrow-backed dtype (extension, dictionary, null), which go through
its block
conversion as before. A NumPy-backed column converts plainly, and a
newly created column
  follows the frame.
- That Arrow-to-pandas type mapping moves unchanged from a closure in
`ArrowBlockAccessor.to_pandas` to module level in `arrow_block.py`, so
both paths share
  one rule.
- A preprocessor that declares no columns falls back to sending the
whole frame.

Writing columns back by position needs `_transform_arrow` to return the
rows it was
given, in order. A changed row count now raises a `ValueError`, and the
`_transform_arrow`
docstring states the contract. All three built-in `_transform_arrow`
implementations are
column transforms and satisfy it.

## Behaviour changes

Both come from untouched columns no longer being re-inferred from Arrow:

- An object column of numbers stays `object`; it used to come back
`int64` / `float64`.
- Integer column labels stay integers; they used to be turned into
strings.

And one for implementers: `_transform_arrow` on a pandas batch now
receives only the
declared input columns, and must not change the rows. The previous code
tolerated a
filtering transform by carrying the index through as a column; it now
raises instead.

## Not a fix for

`enable_arrow_backed_pandas_conversion=False` mitigates this only for
Arrow-block sources.
A pandas block built from an already-Arrow-backed frame — what
`pd.read_parquet(..., dtype_backend="pyarrow")` returns — never
undergoes an
Arrow-to-pandas conversion, so the flag does not reach it; this change
fixes that path.

Two related gaps are left for follow-ups rather than widening this PR:

- `Preprocessor.transform(ds)` has the same stale-metadata defect for a
dataset built from
an Arrow-backed pandas frame with the flag set to `False` (it works with
the default).
- `transform_batch(pa.Table)` returns a table that still carries the
caller's pandas
metadata, so calling `.to_pandas()` on the result can fail the same way.

## Not a duplicate

No open PR touches `_transform_batch` or this pandas/Arrow round trip.
The open
preprocessor work (ray-project#66088, ray-project#66091) is about how preprocessors are
*fitted* and does not
change the transform path; ray-project#60533 adds a `drop` option to the one-hot
encoders in
`encoder.py`. The other open Arrow/pandas PRs are elsewhere: ray-project#65539 is
schema
unification for empty datasets, ray-project#63938 preserves `CategoricalDtype` in
`Schema.types`.

No open issue covers it either. ray-project#64765, the umbrella 2.56 `to_pandas`
regression, is
closed, fixed by ray-project#64768 — which added the
`enable_arrow_backed_pandas_conversion`
opt-out and left this round trip untouched.

## Testing

35 `transform_batch` cases added to

`python/ray/data/tests/preprocessors/test_preprocessors_arrow_backed.py`:

- `test_transform_batch_inside_a_pandas_udf` — the three reported
preprocessors through a
  pandas UDF, parametrized over `enable_arrow_backed_pandas_conversion`.
- `test_transform_batch_on_an_arrow_backed_pandas_block` — the shape the
flag does not cover.
- `test_transform_batch_passes_through_an_untouched_list_column` — the
list-column case.
- `test_transform_batch_matches_the_input_backing` /
`..._decides_the_backing_per_column`
— NumPy in gives NumPy out, Arrow in gives Arrow out, and a mixed frame
keeps both.
- `test_transform_batch_keeps_arrow_backing_with_the_flag_off` — the
same holds for all
three preprocessors with `enable_arrow_backed_pandas_conversion=False`.
- `test_transform_batch_keeps_pass_through_extension_dtypes` — nullable
`Int64`, `boolean`
  and `string` columns come back intact, including a value past 2**53.
- `test_transform_batch_leaves_untouched_columns_exactly_as_they_were` —
object columns of
  numbers, a categorical over pandas strings, Python lists.
- `test_transform_batch_preserves_the_index` — named, `MultiIndex` and
tz-aware
  `DatetimeIndex` on both backings, plus the columns axis name.
- `test_transform_batch_keeps_integer_column_labels`,
`..._does_not_modify_the_callers_frame`,
`..._rejects_a_transform_that_changes_the_row_count`,
  `..._on_an_empty_batch`.

The cases assert on values rather than on "did not raise": where the
stale metadata
permitted the cast, the result was silently wrong rather than an error —
an ordinal
encoding coming back as the strings `"0"`, `"1"`, `"2"`.

Against the unmodified source, 21 of the 35 fail:

- 15 are the reported crash on Arrow-backed input.
- 5 are the behaviour changes above: master re-typed untouched object
and categorical
  columns and stringified integer labels.
- 1 is the new contract: master tolerated a filtering
`_transform_arrow`; this raises.

The other 14 pass on master too and are controls — the NumPy-backed
halves, the empty
batch, and the pass-through dtype cases, which guard against a
regression a naive fix
would introduce.

```
$ PYTHONPATH=python/ray/data/tests python -m pytest -q \
    python/ray/data/tests/preprocessors/ --ignore=.../test_torch.py
381 passed, 5 skipped

$ PYTHONPATH=python/ray/data/tests python -m pytest -q python/ray/data/tests/test_arrow_block.py
30 passed
```

The three reported repros were also run end to end through `map_batches`
in Ray workers.
`test_torch.py` is excluded because `torch` is not installed in this
environment; it is
untouched by this change. Pre-commit passes on all three changed files.

Only the declared columns are converted, so wide frames stop paying for
every column:
`StandardScaler(columns=["n"]).transform_batch` on a 1000-column ×
2k-row NumPy frame
goes from ~27 ms to under 1 ms.

AI assistance was used for this change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Signed-off-by: Aarrya <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Aarrya <[email protected]>
Fitting the encoders through aggregations regressed two cases that worked
with the previous driver-side counting:

- Arrow has no unique/value_counts kernel for extension types such as
  tensors, so a column of arrays raised ArrowNotImplementedError.
- Arrow's uniqueness of a list-typed column needs the optional polars
  package, so whole-list encoding raised ImportError without it.

The encoders now use a private Unique subclass that tries the vectorized
path first and only falls back to collecting the values in Python when
Arrow can't handle the column's type (ArrowNotImplementedError or a
missing polars). Lists and arrays become tuples, matching the categories
the previous implementation produced. TopKUnique likewise falls back to
counting in Python for types without a value_counts kernel, which covers
tensor columns with max_categories.

Transform on tensor columns is unchanged: it already raised on master.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
@abhishekverma-ray
abhishekverma-ray force-pushed the preproc-3-deferred-chain-fit branch from 8bb2247 to dda81e7 Compare October 7, 2026 03:58
…vior

- Remove compute_unique_value_indices and _get_most_frequent_values. The
  encoders and SimpleImputer now fit through aggregations, so nothing calls
  them, and they were never exported.
- Add a test that the default OrdinalEncoder (list encoding on) splits each
  array of a tensor column into its elements, as the previous fit path did.
- Add a test that merging per-block partials keeps array and list categories
  whole, both on the vectorized path and on the Python fallback used when
  polars is not installed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
@abhishekverma-ray
abhishekverma-ray force-pushed the preproc-3-deferred-chain-fit branch from dda81e7 to a4e5924 Compare October 9, 2026 10:14
abhishekverma-ray and others added 3 commits October 16, 2026 11:28
- Move the Python fallback for column types the vectorized path can't
  handle (types without an Arrow unique kernel, such as tensors, and
  list-typed columns when polars isn't installed) from a private encoder
  subclass into Unique itself, matching how TopKUnique handles them. The
  encoders use Unique directly again. HASH list encoding keeps requiring
  polars, since a Python fallback can't reproduce polars hashes.
- Share one _to_hashable helper between Unique and TopKUnique.
- Pin that a missing row in a list column contributes no categories.
- Tests: restore DataContext changes with the restore_data_context fixture,
  and merge the polars and null-sentinel tests into parametrized ones.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
Adds an opt-in fast path for fitting preprocessor Chains, gated on the
new DataContext.enable_aggregation_based_preprocessors setting (env:
RAY_DATA_ENABLE_AGGREGATION_BASED_PREPROCESSORS, default off).

Today Chain.fit() runs one full dataset scan per fittable member (and
each scan re-executes the lazy upstream pipeline). With the flag on,
fit() only registers each member's statistics as aggregation queries;
the first transform() builds a column-dependency DAG - a later member
depends on an earlier one iff it reads a column the earlier one writes -
and computes all aggregations with satisfied dependencies in a single
Dataset.aggregate() call, one scan per dependency level instead of one
per member. Statistics are computed over the dataset passed to fit()
(not the transformed dataset), so fit semantics and results are
identical to sequential fitting.

Mechanics:
- Preprocessor gains a _supports_deferred_fit marker; only classes whose
  _fit purely registers plan aggregators are marked (StandardScaler,
  SimpleImputer, and the five encoders from the previous commit). A
  chain containing any unmarked fittable member keeps today's sequential
  eager fit, so third-party and legacy preprocessors are unaffected.
- New preprocessors/dag.py builds the DAG; non-fittable members become
  placeholder nodes that carry their read/write columns, so a fittable
  member reading e.g. a Concatenator output only aggregates after that
  transform is applied.
- StatComputationPlan's aggregate execution is extracted into a shared
  execute_aggregate_specs helper; nodes needing the same alias in one
  level run in separate query batches instead of colliding.

Safety valves included in this change:
- Serial fallback (with a warning) when any member registered a custom
  callable stat.
- Idempotence: repeated transform()/transform_batch() never re-runs the
  aggregations.
- Serialization and plain pickling of a fitted-but-never-transformed
  chain materialize the deferred statistics first, in dependency order;
  the fit dataset itself is never pickled.
- transform_batch() also materializes deferred statistics.
- Nested chains defer recursively and fit on the data flowing into their
  chain position.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
- Cast the aggregate spec's stat_fn to AggregateFnV2 in _AggregationNode.agg_fn.
  Aggregate specs always hold an aggregation (callable stats are separate
  specs), but the spec's attribute is typed as a broader union, which pyrefly
  rejects as a return type.
- Refer to DataContext.enable_aggregation_based_preprocessors with a literal
  in the Chain docstring instead of a :attr: role. The setting is not a
  documentable target, and docs build warnings are treated as errors.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
@abhishekverma-ray
abhishekverma-ray force-pushed the preproc-3-deferred-chain-fit branch from a4e5924 to a8eb701 Compare October 16, 2026 06:05
goutamvenkat-anyscale pushed a commit that referenced this pull request Oct 16, 2026
…ggregation (#66088)

## Why are these changes needed?

Encoder preprocessors (`OrdinalEncoder`, `OneHotEncoder`,
`MultiHotEncoder`,
`LabelEncoder`, `Categorizer`) currently fit through
`compute_unique_value_indices`: a `map_batches` that emits per-block
value
counters, followed by a loop **on the driver** that merges them into
global
counts. `SimpleImputer(strategy="most_frequent")` has the same shape via
`_get_most_frequent_values`. That driver-side merge is a scalability
bottleneck, and because it is registered as a *callable stat*, it can
never be
batched with other statistics into a single `Dataset.aggregate()` query.

This PR moves those fits onto the stat computation plan as real
distributed
aggregations:

- The five encoders register `Unique` (or `TopKUnique` when
`max_categories`
is set) with the same `unique_values({col})` alias the transform code
reads.
- `SimpleImputer("most_frequent")` registers `TopKUnique(k=1,
ignore_nulls=True)`.
It returns the most frequent non-null value, breaks frequency ties by
picking
the smallest value, and yields no value for an all-null column, which
gives
the same results as before. It uses the vectorized column-wise merge, so
no
  driver-side argmax helper is needed.
- `Unique` (and `TopKUnique`) fall back to collecting values in Python
when
the vectorized path can't handle a column's type: types without an Arrow
  `unique`/`value_counts` kernel, such as tensor columns, and list-typed
  columns when the optional `polars` package isn't installed. Lists and
  arrays become tuples, so the encoders produce the same categories as
  before. `HASH` list encoding still requires `polars`, since a Python
  fallback can't reproduce polars' hashes.

Behavior is preserved: `stats_` key names, the "contains null values …
consider imputing" errors, list-column encoding (flatten vs whole-list),
and
global cross-partition top-k semantics for `max_categories` are all
unchanged,
which the existing suites verify. Each fit is now a single
`Dataset.aggregate()` query per preprocessor with no driver-side merge.

The legacy helpers `compute_unique_value_indices` and
`_get_most_frequent_values` are removed; nothing uses them.

Behavior notes for reviewers:

- `ds.aggregate(Unique(...))` on a tensor column, or on a list column
without
  `polars` installed, now works instead of raising. This comes from the
  fallback above and benefits any `Unique` user, not only the encoders.
- Whole-list categories stay whole lists when merged from several
partial
  aggregates, with or without `polars` (see the new tests below).
- With `max_categories`, a null tied with a real value at the cut-off no
longer raises "contains null values": nulls now rank last, whereas the
old
path broke ties by insertion order. Otherwise it raises in the same
cases
  as before.
- Pre-existing and unchanged: a block that holds *only* null rows of a
list
column is typed `null` rather than `list`, so its nulls count as a value
and the fit raises. This depends on how rows are split into blocks, as
it
  did before this PR; I'll file a follow-up.

## Related issue number

N/A. Not a duplicate: searched open PRs/issues for encoder/imputer fit
work;
no overlap found (#66012 covers GPU transforms, not fitting).

Part 2 of 4 of the preprocessor fitting series (RFC: #66090). Part 1
(`TopKUnique`, #66087) has merged; parts 3 and 4 (#66091, #66092) build
on this.

## Checks

- [x] I've signed off every commit (DCO).
- [x] I've run pre-commit hooks — all hooks pass.
- [x] Testing (macOS / Python 3.12, source build):
- `pytest python/ray/data/tests/preprocessors/
--ignore=.../test_torch.py`
    (torch not installed) — 411 passed, 5 skipped, 0 failed
    (clean master at the same base: 392 passed). Includes
`test_preprocessors_arrow_backed.py`. Env matches CI pins (pandas 2.3.3,
    pyarrow 23.0.1, cloudpickle 3.1.1).
  - `pytest python/ray/data/tests/test_aggregations.py` — 62 passed
    (clean master: 57).
- New tests: encoders/imputer assert they register plan aggregators (no
callable stats); most_frequent never imputes null (including `None`,
`NaN`,
`pd.NA` and float32 `NaN`, even when they outnumber every real value);
deterministic tie-break; most_frequent picks the value from counts
summed
across blocks; whole-list categories
(`OrdinalEncoder(encode_lists=False)`,
    `OneHotEncoder`) stay whole lists when merged from several partial
aggregates; encoders fit tensor columns (whole arrays, flattened arrays,
    `max_categories`); whole-list encoding with and without `polars`;
`Unique` on tensor columns and on list columns without `polars`; `HASH`
    mode still requires `polars`; a null row in a list column adds no
    categories.

AI assistance was used to draft this change (Claude Code); every line
has been
reviewed by the submitter.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Abhishek Verma <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
@abhishekverma-ray
abhishekverma-ray marked this pull request as ready for review October 19, 2026 02:46
@abhishekverma-ray
abhishekverma-ray requested a review from a team as a code owner October 19, 2026 02:46
@abhishekverma-ray abhishekverma-ray added data Ray Data-related issues go add ONLY when ready to merge, run all tests labels Oct 19, 2026

@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 deferred, aggregation-based fitting for preprocessor chains in Ray Data, allowing independent preprocessors' aggregations to be batched into a single dataset scan. It also adds Python fallbacks for Unique and TopKUnique aggregators to handle unsupported Arrow types like tensors. The review feedback suggests several key improvements: making the _to_hashable helper recursive to robustly handle nested structures, refining get_input_columns and get_output_columns in Chain to exclude intermediate columns and remove duplicates, and clearing the stashed fit dataset self._fit_ds after statistics materialization to prevent memory retention issues.

Comment on lines +1185 to +1190
def _to_hashable(value: Any) -> Any:
"""Make a list-like value usable as a set member or dict key.

Lists, tuples and arrays become tuples; anything else is returned as is.
"""
return tuple(value) if isinstance(value, (list, tuple, np.ndarray)) else value

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.

high

The _to_hashable function only converts the top-level of list-like values to a tuple. If the column contains multidimensional arrays or nested lists (which is common for tensor columns), tuple(value) will produce a tuple containing unhashable np.ndarray or list objects, leading to a TypeError: unhashable type when added to a set or dict. Making this conversion recursive ensures robust handling of nested structures.

Suggested change
def _to_hashable(value: Any) -> Any:
"""Make a list-like value usable as a set member or dict key.
Lists, tuples and arrays become tuples; anything else is returned as is.
"""
return tuple(value) if isinstance(value, (list, tuple, np.ndarray)) else value
def _to_hashable(value: Any) -> Any:
"""Make a list-like value usable as a set member or dict key.
Lists, tuples and arrays become tuples recursively; anything else is returned as is.
"""
if isinstance(value, np.ndarray):
value = value.tolist()
if isinstance(value, (list, tuple)):
return tuple(_to_hashable(x) for x in value)
return value

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.

Not changing this here. Master raises the same unhashable type error for 2-D tensor columns, transform on tensor columns isn’t supported anyway, and this helper belongs to #66088.

Comment thread python/ray/data/preprocessors/chain.py Resolved
Comment thread python/ray/data/preprocessors/chain.py Resolved
Comment thread python/ray/data/preprocessors/chain.py Resolved

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

Stale Bugbot comment from a previous run.

Comment thread python/ray/data/preprocessors/dag.py Resolved
Comment thread python/ray/data/preprocessors/chain.py Resolved
Fix cases where a deferred Chain fit computed different statistics than
fitting the members one by one:

- A member that doesn't declare its input/output columns (the default for
  user-defined preprocessors) may read or write any column. Treat it as a
  barrier in the dependency DAG, so later members compute statistics only
  after its transform is applied. Previously, a custom step rewriting a
  column in place was ignored and later members fit on untransformed data.
  A nested Chain declares its columns only if every member does.
- Apply transforms strictly in chain order, and consider a member ready
  only once the members it depends on have been transformed. Previously a
  later member could rewrite a column before an earlier member computed
  its statistics on it.
- Run every aggregation registered on a member's plan, even if stats_ is
  already partly filled. Categorizer copies the dtypes it was given into
  stats_ first, so columns without a given dtype were never inferred
  (both in the batched path and in the serial fallback).

Also:
- Release the stashed fit dataset once the statistics are computed, so a
  fitted chain doesn't keep the training dataset alive.
- Chain.get_input_columns() no longer lists columns produced inside the
  chain, and both column lists are de-duplicated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>

@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 fbf33f3. Configure here.

Comment thread python/ray/data/preprocessors/dag.py Resolved
abhishekverma-ray and others added 2 commits October 19, 2026 10:55
… fit

A user-defined member that sets `columns` and rewrites them in place
declares input columns but no output columns, so the deferred-fit DAG
didn't treat it as writing anything, and later members computed their
statistics on untransformed data. A member now counts as declaring its
columns only if it declares both inputs and outputs; otherwise it's a
barrier. All built-in preprocessors declare both.

Also skip non-fittable members when checking for custom stat functions,
so a user-defined member that doesn't call `Preprocessor.__init__` no
longer raises an AttributeError.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
The `ray.data` logger doesn't propagate to the root logger, so with the
pytest version CI pins, `caplog` never saw the fallback warning. Use the
`propagate_logs` fixture, as other Ray Data tests that read logs do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
Comment on lines +108 to +115
columns = {}
written = set()
for p in self._preprocessors:
for column in p.get_input_columns():
if column not in written:
columns[column] = None
written.update(p.get_output_columns())
return list(columns)

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.

can't columns just be a set as well?

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.

I kept a dict so the result is in chain order and stable from run to run; a set of strings can iterate in a different order in each process. The scheduler turns these into sets anyway.

not p._is_fittable or p._supports_deferred_fit for p in self._preprocessors
)

def get_input_columns(self) -> List[str]:

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.

This should be a frozenList no?

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.

These override Preprocessor.get_input_columns/get_output_columns, which return List[str], so I kept the same type. Each call builds a new list, so callers can't change the chain through it. Did you mean something else, e.g. _preprocessors (already a tuple)?

# everything now and defer the scans to `_materialize_deferred_stats`,
# which computes them level-by-level over the fit dataset.
for preprocessor in self._preprocessors:
if not preprocessor._is_fittable:

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.

When is a preprocessor not fittable?

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.

When the preprocessor needs no statistics: Concatenator, Normalizer, Tokenizer, HashingVectorizer, FeatureHasher, PowerTransformer, CustomKBinsDiscretizer, SimpleImputer(strategy="constant"), and most user-defined preprocessors. There's nothing to register, so we skip them here and just apply their transform later.

Comment on lines +136 to +139
if self._uses_deferred_fit():
# Every member's `_fit` only registers aggregations, so no member
# needs the previous members' transformed output to fit: register
# everything now and defer the scans to `_materialize_deferred_stats`,

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.

Can you give me an example of when this is true?

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.

It's true when the flag is on and every fittable member only registers aggregations in _fit, e.g. Chain(SimpleImputer(["a"]), StandardScaler(["a"]), OrdinalEncoder(["c"])). If the flag is off, or any fittable member can't defer (e.g. CountVectorizer, UniformKBinsDiscretizer, or a user-defined subclass), the whole chain fits eagerly as it does today.

Comment thread python/ray/data/preprocessors/chain.py Outdated
Comment on lines +170 to +172
getattr(self, "_deferred_fit", False)
and not getattr(self, "_stats_materialized", False)
and getattr(self, "_fit_ds", None) is not None

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.

Let's not use getattr

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.

Done in d068ebd. Both deserialization paths (__setstate__ and _set_serializable_fields) already set these fields, so I switched to plain attribute access.

@goutamvenkat-anyscale

goutamvenkat-anyscale commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Suggestion: two changes, in order

  1. Replace the runtime node DAG with precomputed levels (_fit_levels) — same schedule, far less machinery.
  2. On top of that, fit in a reordered sequence (_fit_order) — removes the extra scan the chain-order executor pays on independent members.

Change 1: _fit_levels(preprocessors) -> List[int] instead of a runtime DAG

The scheduler currently builds a node per (member, aggregation), wires dependency/dependent sets, validates acyclicity (impossible by construction — edges only point backward in the chain), and re-derives the schedule at runtime in a while loop over mutable node state. But the schedule is static and collapses to one integer per member: a layered topological sort of the column DAG. Each level is one Dataset.aggregate() scan, and the executor becomes a plain for loop.

On Chain(StandardScaler(["A","B"]), SimpleImputer(["B"]), LabelEncoder("C")) — the imputer reads B, which the scaler writes; the encoder is independent:

flowchart TB
    subgraph Before["Before — runtime DAG in _materialize_deferred_stats"]
        direction TB
        B1["_build_aggregation_dag: 6 nodes<br/>(one per member x aggregation, placeholders for the rest)"]
        B2["edges: imputer's mean(B) node depends on<br/>all 4 scaler nodes (identical edges, duplicated)"]
        B3["_validate_dag_is_acyclic<br/>(cycles impossible by construction)"]
        B4["while pending: find ready nodes via dependency sets,<br/>scan, mutate completed flags, transform, repeat"]
        B1 --> B2 --> B3 --> B4
    end
    subgraph After["After — precomputed levels"]
        direction TB
        A1["_fit_levels(chain) == [0, 1, 0]<br/>(pure function, 15 lines)"]
        A2["level 0: one scan over raw data:<br/>mean/std(A,B) + unique_values(C), then scaler transforms"]
        A3["level 1: one scan over scaled data:<br/>mean(B), then imputer + encoder transform"]
        A1 --> A2 --> A3
    end
    OUT["identical outcome: 2 scans, same stats_ as sequential fitting"]
    B4 --> OUT
    A3 --> OUT
    classDef removed fill:#ffcdd2,stroke:#c62828,color:#000
    classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000
    class B1,B2,B3,B4 removed
    class A1,A2,A3 added
Loading

Net: dag.py goes from ~160 lines (node classes, edge loops, cycle check) to two pure functions testable without a dataset, and the executor needs no termination argument.

Change 2: _fit_order — fit in a reordered sequence

Change 1 alone applies transforms strictly in chain order, so an independent pair downstream of a slower pair pays an extra scan: [scaler(x), imputer(x), scaler(y), imputer(y)] has levels [0, 1, 0, 2] — 3 scans — because scaler(y)'s transform sits behind the unfitted imputer(x). _fit_order fixes this with a stable sort by level in the conflict graph — pairs that touch (read or write) any common column, plus undeclared-column members as barriers. Read-read overlaps count as conflicts too, because a transform may consume the columns it reads (Concatenator drops its inputs). Conflicting pairs keep chain order; truly disjoint members regroup:

levels in chain order:  [0, 1, 0, 2]   -> 3 scans
fit order:              [scaler(x), scaler(y), imputer(x), imputer(y)]
levels in fit order:    [0, 0, 1, 1]   -> 2 scans

Only the fit-time pipeline is permuted — the stored chain and inference-time transform order are untouched. Tests count the actual aggregate() calls (3 → 2, statistics identical to sequential fitting) and pin two hazard cases: a Concatenator that overwrites x keeps its position behind the imputer reading x, and a Concatenator that reads-and-drops y keeps its position behind another reader of y.

This change is what makes deleting the downstream Chain implementation scan-count neutral: that implementation already applies transforms out of dependency order, so without _fit_order the migration would regress exactly this pattern — while _fit_order keeps the ordering deterministic and hazard-safe, which the downstream version is not.

_fit_levels and the one subtlety
def _fit_levels(preprocessors: Sequence[Preprocessor]) -> List[int]:
    declares = [_declares_columns(p) for p in preprocessors]
    reads = [set(p.get_input_columns()) for p in preprocessors]
    writes = [set(p.get_output_columns()) for p in preprocessors]

    levels, prefix_levels = [], []
    for i in range(len(preprocessors)):
        level = 0
        for j in range(i):
            if not declares[i] or not declares[j] or reads[i] & writes[j]:
                level = max(level, prefix_levels[j] + 1)
        levels.append(level)
        prefix_levels.append(max(level, prefix_levels[i - 1]) if i else level)
    return levels

The prefix_levels running max (rather than levels[j] + 1) encodes that transforms apply in order: depending on member j means waiting for every member before j too. Pinned by a test:

a, b = StandardScaler(["x"]), SimpleImputer(["x"])
c, d = StandardScaler(["y"]), SimpleImputer(["y"])
assert _fit_levels([a, b, c, d]) == [0, 1, 0, 2]  # d waits for b's level, not just c's

(Change 2's _fit_order is what removes exactly this wait when the pairs don't conflict.)

Scan-for-scan identical or better than the current implementation; all 32 existing test_chain.py tests pass unchanged, plus new tests for the levels, the fit order, and the measured scan reduction. Pushed as 09b1caf on this branch — feel free to review, amend, or revert it.

(Written and implemented with AI assistance; reviewed and tested locally.)

goutamvenkat-anyscale and others added 2 commits October 22, 2026 15:37
…e reordering

Replace the per-(member, aggregation) node DAG with two pure functions:

- _fit_levels: a layered topological sort of the column-dependency graph,
  returning one scan level per member. Each level runs as one
  Dataset.aggregate() call and the executor is a bounded for loop - no node
  objects, no mutable scheduling state, no cycle check (edges only point
  backward in the chain, so cycles are impossible by construction).
- _fit_order: a fit-time permutation (stable sort by conflict-graph level)
  so members touching disjoint columns share the earliest scan possible.
  Conflicts are any shared touched column - including read-read, since a
  transform may consume the columns it reads (Concatenator drops its
  inputs) - plus undeclared-column members as barriers. Only the fit-time
  pipeline is reordered; the stored chain and inference-time transform
  order are unchanged.

The scan schedule is identical to the previous implementation, or better:
[scaler(x), imputer(x), scaler(y), imputer(y)] drops from 3 scans to 2
because both scalers share the first scan. Tests count the actual
aggregate() calls and pin the reordering hazard cases.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Goutam <[email protected]>
Add a test that fit-time reordering never moves members across a member
that doesn't declare its columns; removing that rule from `_fit_order`
previously left every test passing, while a rescaler then fit on the
wrong data. Also:

- Correct docstrings and a comment that still described transforms as
  applied in chain order or overstated which members are applied
  before a level's scan.
- Document that deferred fitting trusts declared columns, so members
  that add or drop rows must not declare both their inputs and outputs.
- Drop the `getattr` calls in `_needs_stats_materialization`; both
  deserialization paths already set these fields.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Abhishek Verma <[email protected]>
@abhishekverma-ray

Copy link
Copy Markdown
Contributor Author

Suggestion: two changes, in order

  1. Replace the runtime node DAG with precomputed levels (_fit_levels) — same schedule, far less machinery.
  2. On top of that, fit in a reordered sequence (_fit_order) — removes the extra scan the chain-order executor pays on independent members.

Change 1: _fit_levels(preprocessors) -> List[int] instead of a runtime DAG

The scheduler currently builds a node per (member, aggregation), wires dependency/dependent sets, validates acyclicity (impossible by construction — edges only point backward in the chain), and re-derives the schedule at runtime in a while loop over mutable node state. But the schedule is static and collapses to one integer per member: a layered topological sort of the column DAG. Each level is one Dataset.aggregate() scan, and the executor becomes a plain for loop.

On Chain(StandardScaler(["A","B"]), SimpleImputer(["B"]), LabelEncoder("C")) — the imputer reads B, which the scaler writes; the encoder is independent:

flowchart TB
    subgraph Before["Before — runtime DAG in _materialize_deferred_stats"]
        direction TB
        B1["_build_aggregation_dag: 6 nodes<br/>(one per member x aggregation, placeholders for the rest)"]
        B2["edges: imputer's mean(B) node depends on<br/>all 4 scaler nodes (identical edges, duplicated)"]
        B3["_validate_dag_is_acyclic<br/>(cycles impossible by construction)"]
        B4["while pending: find ready nodes via dependency sets,<br/>scan, mutate completed flags, transform, repeat"]
        B1 --> B2 --> B3 --> B4
    end
    subgraph After["After — precomputed levels"]
        direction TB
        A1["_fit_levels(chain) == [0, 1, 0]<br/>(pure function, 15 lines)"]
        A2["level 0: one scan over raw data:<br/>mean/std(A,B) + unique_values(C), then scaler transforms"]
        A3["level 1: one scan over scaled data:<br/>mean(B), then imputer + encoder transform"]
        A1 --> A2 --> A3
    end
    OUT["identical outcome: 2 scans, same stats_ as sequential fitting"]
    B4 --> OUT
    A3 --> OUT
    classDef removed fill:#ffcdd2,stroke:#c62828,color:#000
    classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000
    class B1,B2,B3,B4 removed
    class A1,A2,A3 added
Loading

Net: dag.py goes from ~160 lines (node classes, edge loops, cycle check) to two pure functions testable without a dataset, and the executor needs no termination argument.

Change 2: _fit_order — fit in a reordered sequence

Change 1 alone applies transforms strictly in chain order, so an independent pair downstream of a slower pair pays an extra scan: [scaler(x), imputer(x), scaler(y), imputer(y)] has levels [0, 1, 0, 2] — 3 scans — because scaler(y)'s transform sits behind the unfitted imputer(x). _fit_order fixes this with a stable sort by level in the conflict graph — pairs that touch (read or write) any common column, plus undeclared-column members as barriers. Read-read overlaps count as conflicts too, because a transform may consume the columns it reads (Concatenator drops its inputs). Conflicting pairs keep chain order; truly disjoint members regroup:

levels in chain order:  [0, 1, 0, 2]   -> 3 scans
fit order:              [scaler(x), scaler(y), imputer(x), imputer(y)]
levels in fit order:    [0, 0, 1, 1]   -> 2 scans

Only the fit-time pipeline is permuted — the stored chain and inference-time transform order are untouched. Tests count the actual aggregate() calls (3 → 2, statistics identical to sequential fitting) and pin two hazard cases: a Concatenator that overwrites x keeps its position behind the imputer reading x, and a Concatenator that reads-and-drops y keeps its position behind another reader of y.

This change is what makes deleting the downstream Chain implementation scan-count neutral: that implementation already applies transforms out of dependency order, so without _fit_order the migration would regress exactly this pattern — while _fit_order keeps the ordering deterministic and hazard-safe, which the downstream version is not.

_fit_levels and the one subtlety

def _fit_levels(preprocessors: Sequence[Preprocessor]) -> List[int]:
    declares = [_declares_columns(p) for p in preprocessors]
    reads = [set(p.get_input_columns()) for p in preprocessors]
    writes = [set(p.get_output_columns()) for p in preprocessors]

    levels, prefix_levels = [], []
    for i in range(len(preprocessors)):
        level = 0
        for j in range(i):
            if not declares[i] or not declares[j] or reads[i] & writes[j]:
                level = max(level, prefix_levels[j] + 1)
        levels.append(level)
        prefix_levels.append(max(level, prefix_levels[i - 1]) if i else level)
    return levels

The prefix_levels running max (rather than levels[j] + 1) encodes that transforms apply in order: depending on member j means waiting for every member before j too. Pinned by a test:

a, b = StandardScaler(["x"]), SimpleImputer(["x"])
c, d = StandardScaler(["y"]), SimpleImputer(["y"])
assert _fit_levels([a, b, c, d]) == [0, 1, 0, 2]  # d waits for b's level, not just c's

(Change 2's _fit_order is what removes exactly this wait when the pairs don't conflict.)

Scan-for-scan identical or better than the current implementation; all 32 existing test_chain.py tests pass unchanged, plus new tests for the levels, the fit order, and the measured scan reduction. Pushed as 09b1caf on this branch — feel free to review, amend, or revert it.

(Written and implemented with AI assistance; reviewed and tested locally.)

Thanks for pushing this, @goutamvenkat-anyscale. I reviewed it end to end: the full preprocessor suites pass, and a brute-force check over 200k random chains found no case where a member fits before the data it needs is ready.

On top (d068ebd) I:

  • added a test pinning that fit-time reordering never moves members across one without declared columns (removing that rule from _fit_order previously left every test passing, while a later scaler fit on the wrong data),
  • fixed three docstrings/comments that still described chain-order transforms or overstated which members are applied before a scan,
  • documented in the Chain docstring that deferred fitting trusts declared columns, so a member that adds or drops rows must not declare both its inputs and outputs,
  • dropped the getattr calls.

@goutamvenkat-anyscale
goutamvenkat-anyscale merged commit 5bcb8d0 into ray-project:master Oct 23, 2026
6 checks passed
goutamvenkat-anyscale pushed a commit that referenced this pull request Oct 26, 2026
…t; migrate remaining scalers (#66092)

## Summary

Turns on deferred, batched `Chain` fitting by default (added behind a
flag in #66091), and moves the three remaining scalers onto
aggregation-based fitting so they batch inside chains too.

## Before

- `DataContext.enable_aggregation_based_preprocessors` defaulted to
`False`, so `Chain.fit()` fitted members one by one: one full dataset
scan per fittable member.
- Even with the flag on, `MinMaxScaler`, `MaxAbsScaler` and
`RobustScaler` ran their own `Dataset.aggregate()` inside `_fit`, so any
chain containing them fell back to the sequential path.

## After

- The flag defaults to `True`: `Chain.fit()` registers members'
aggregations and computes them at the first `transform()` (or
`transform_batch()` / serialization), one scan per dependency level. Opt
out with `RAY_DATA_ENABLE_AGGREGATION_BASED_PREPROCESSORS=0` or the
`DataContext` setting. The flip is isolated in this PR so it's trivially
revertible.
- `MinMaxScaler` (`Min`/`Max`), `MaxAbsScaler` (`AbsMax`) and
`RobustScaler` register aggregators on the stat computation plan and
support deferred fit.
- `RobustScaler` now builds one single-quantile `ApproximateQuantile`
sketch per statistic (`low_quantile`, `median`, `high_quantile`) instead
of one sketch queried at three points. That's a little more sketch work,
in exchange for keeping every `stats_` key unchanged.
- All `stats_` keys and values are unchanged. KBins discretizers keep
their eager fit (they post-process in `_fit_execute`); chains containing
them, or any member without `_supports_deferred_fit`, still fit
sequentially.

```mermaid
flowchart TD
    subgraph Before
        subgraph BS[Subsystem: preprocessors]
            subgraph BC["Component: Chain.fit() (flag default off)"]
                B1[MinMaxScaler._fit: own aggregate scan] --> B2[MaxAbsScaler._fit: own aggregate scan]
                B2 --> B3[RobustScaler._fit: own aggregate scan]
                B3 --> B4[StandardScaler._fit: own aggregate scan]
            end
        end
    end
    subgraph After
        subgraph AS[Subsystem: preprocessors]
            subgraph AC["Component: Chain.fit() (flag default on)"]
                A1[MinMax / MaxAbs / Robust / Standard: register aggregators on plan]
                A1 --> A2["first transform(): one Dataset.aggregate() per dependency level"]
            end
        end
    end
    classDef removed fill:#ffcdd2,stroke:#c62828,color:#000
    classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000
    classDef changed fill:#fff9c4,stroke:#f9a825,color:#000
    class B1,B2,B3,B4 removed
    class A1 changed
    class A2 added
```

## Subsystems

Preprocessors (`preprocessors/scaler.py`, default in `context.py`);
computes statistics through Shuffle / aggregation (`Dataset.aggregate`)
with no changes there.

## Related issue

RFC: #66090. Final PR of the stack #66087 → #66088 → #66091 (all
merged). Not a duplicate: the only open PR touching this flag is this
one.

## Testing

macOS / Python 3.12, env pinned to CI versions (pandas 2.3.3, pyarrow
23.0.1, cloudpickle 3.1.1, pytest 7.4.4):

- `pytest python/ray/data/tests/preprocessors/test_chain.py
python/ray/data/tests/preprocessors/test_scaler.py`: 64 passed,
including a new test that a chain of MinMax/MaxAbs/Robust/Standard
scalers on disjoint columns fits in a single aggregation query with the
exact expected `stats_`. Existing `test_scaler.py` assertions pass
unmodified.
- `pytest python/ray/data/tests/preprocessors/
--ignore=python/ray/data/tests/preprocessors/test_torch.py` (torch not
installed): 442 passed, 5 skipped, 0 failed (master: 441 passed).
- `pytest python/ray/data/tests/test_aggregations.py`: 62 passed.
- pre-commit, pyrefly (CI file set) and the API param coverage check
pass.

AI assistance was used to draft this change (Claude Code); every line
has been reviewed by the submitter.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: Abhishek Verma <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
justinyeh1995 pushed a commit to justinyeh1995/ray that referenced this pull request Oct 28, 2026
…t; migrate remaining scalers (ray-project#66092)

## Summary

Turns on deferred, batched `Chain` fitting by default (added behind a
flag in ray-project#66091), and moves the three remaining scalers onto
aggregation-based fitting so they batch inside chains too.

## Before

- `DataContext.enable_aggregation_based_preprocessors` defaulted to
`False`, so `Chain.fit()` fitted members one by one: one full dataset
scan per fittable member.
- Even with the flag on, `MinMaxScaler`, `MaxAbsScaler` and
`RobustScaler` ran their own `Dataset.aggregate()` inside `_fit`, so any
chain containing them fell back to the sequential path.

## After

- The flag defaults to `True`: `Chain.fit()` registers members'
aggregations and computes them at the first `transform()` (or
`transform_batch()` / serialization), one scan per dependency level. Opt
out with `RAY_DATA_ENABLE_AGGREGATION_BASED_PREPROCESSORS=0` or the
`DataContext` setting. The flip is isolated in this PR so it's trivially
revertible.
- `MinMaxScaler` (`Min`/`Max`), `MaxAbsScaler` (`AbsMax`) and
`RobustScaler` register aggregators on the stat computation plan and
support deferred fit.
- `RobustScaler` now builds one single-quantile `ApproximateQuantile`
sketch per statistic (`low_quantile`, `median`, `high_quantile`) instead
of one sketch queried at three points. That's a little more sketch work,
in exchange for keeping every `stats_` key unchanged.
- All `stats_` keys and values are unchanged. KBins discretizers keep
their eager fit (they post-process in `_fit_execute`); chains containing
them, or any member without `_supports_deferred_fit`, still fit
sequentially.

```mermaid
flowchart TD
    subgraph Before
        subgraph BS[Subsystem: preprocessors]
            subgraph BC["Component: Chain.fit() (flag default off)"]
                B1[MinMaxScaler._fit: own aggregate scan] --> B2[MaxAbsScaler._fit: own aggregate scan]
                B2 --> B3[RobustScaler._fit: own aggregate scan]
                B3 --> B4[StandardScaler._fit: own aggregate scan]
            end
        end
    end
    subgraph After
        subgraph AS[Subsystem: preprocessors]
            subgraph AC["Component: Chain.fit() (flag default on)"]
                A1[MinMax / MaxAbs / Robust / Standard: register aggregators on plan]
                A1 --> A2["first transform(): one Dataset.aggregate() per dependency level"]
            end
        end
    end
    classDef removed fill:#ffcdd2,stroke:#c62828,color:#000
    classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000
    classDef changed fill:#fff9c4,stroke:#f9a825,color:#000
    class B1,B2,B3,B4 removed
    class A1 changed
    class A2 added
```

## Subsystems

Preprocessors (`preprocessors/scaler.py`, default in `context.py`);
computes statistics through Shuffle / aggregation (`Dataset.aggregate`)
with no changes there.

## Related issue

RFC: ray-project#66090. Final PR of the stack ray-project#66087 → ray-project#66088 → ray-project#66091 (all
merged). Not a duplicate: the only open PR touching this flag is this
one.

## Testing

macOS / Python 3.12, env pinned to CI versions (pandas 2.3.3, pyarrow
23.0.1, cloudpickle 3.1.1, pytest 7.4.4):

- `pytest python/ray/data/tests/preprocessors/test_chain.py
python/ray/data/tests/preprocessors/test_scaler.py`: 64 passed,
including a new test that a chain of MinMax/MaxAbs/Robust/Standard
scalers on disjoint columns fits in a single aggregation query with the
exact expected `stats_`. Existing `test_scaler.py` assertions pass
unmodified.
- `pytest python/ray/data/tests/preprocessors/
--ignore=python/ray/data/tests/preprocessors/test_torch.py` (torch not
installed): 442 passed, 5 skipped, 0 failed (master: 441 passed).
- `pytest python/ray/data/tests/test_aggregations.py`: 62 passed.
- pre-commit, pyrefly (CI file set) and the API param coverage check
pass.

AI assistance was used to draft this change (Claude Code); every line
has been reviewed by the submitter.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: Abhishek Verma <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
richardliaw pushed a commit that referenced this pull request Nov 18, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

2 participants