Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
0ab40d3
engine-execute
madsbk Jul 7, 2026
f6b13b4
Merge branch 'main' of github.com:rapidsai/cudf into engine-execute
madsbk Jul 14, 2026
7205d67
Apply suggestions from code review
madsbk Jul 14, 2026
8d90be0
Merge branch 'engine-execute' of github.com:madsbk/cudf into engine-e…
madsbk Jul 14, 2026
6f191ec
drop_unserializable
madsbk Jul 14, 2026
e432825
docs
madsbk Jul 14, 2026
2cf36c4
Merge branch 'main' of github.com:rapidsai/cudf into engine-execute
madsbk Jul 14, 2026
73ea282
test_in_memory_executor_drop_unserializable
madsbk Jul 14, 2026
63cb5bf
cleanup
madsbk Jul 14, 2026
fee2d46
Merge branch 'main' of github.com:rapidsai/cudf into engine-execute
madsbk Jul 14, 2026
36bae2c
test_engine_execute.py: import at module level
madsbk Jul 14, 2026
b4b3ae0
check_row_order=True
madsbk Jul 14, 2026
ba7b646
with pytest.RaisesGroup
madsbk Jul 15, 2026
a2ded82
pytest.RaisesExc(RuntimeError, ...)
madsbk Jul 15, 2026
4253cef
Merge branch 'main' of github.com:rapidsai/cudf into engine-execute
madsbk Jul 15, 2026
8db4297
RankLocalStore: avoid lock
madsbk Jul 15, 2026
437bedb
avoid _stores_lock
madsbk Jul 15, 2026
7159bc6
Apply suggestions from code review
madsbk Jul 15, 2026
05d1181
Apply suggestions from code review
madsbk Jul 15, 2026
1279764
Merge branch 'main' of github.com:rapidsai/cudf into engine-execute
madsbk Jul 15, 2026
4b99b43
docs
madsbk Jul 15, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/cudf/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -635,13 +635,17 @@ def on_missing_reference(app, env, node, contnode):
("py:class", "Options"),
# polars aliases that don't match the public intersphinx targets.
("py:class", "pl.DataFrame"),
("py:class", "pl.DataType"),
("py:class", "pl.Expr"),
("py:class", "pl.GPUEngine"),
("py:class", "pl.LazyFrame"),
("py:class", "polars.LazyFrame"),
("py:class", "polars.DataFrame"),
("py:class", "polars.dataframe.frame.DataFrame"),
# Sphinx isn't able to resolve this cudf-polars.quent type alias
("py:class", "Value"),
("py:class", "polars.lazyframe.frame.LazyFrame"),
Comment thread
TomAugspurger marked this conversation as resolved.
Resolved
("py:class", "cudf_polars.engine.persisted_result.PersistedBackend"),
]
# Temporarily disable nitpick warnings for pandas: https://github.com/pandas-dev/pandas/issues/64584
nitpick_ignore_regex = [
Expand Down
9 changes: 9 additions & 0 deletions docs/cudf/source/cudf_polars/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,15 @@ The engine classes share a common base class:
:members:
```

## Persisted results

Returned by `engine.execute()` to keep query results GPU-resident (see {doc}`execute`).

```{eval-rst}
.. autoclass:: cudf_polars.engine.persisted_result.PersistedQueryResult
:members: lazy, release
```

## Configuration

```{eval-rst}
Expand Down
127 changes: 127 additions & 0 deletions docs/cudf/source/cudf_polars/execute.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
(cudf-polars-execute)=
# Keeping results on the GPU with `engine.execute()`

```{warning}
`engine.execute()` is **experimental**. Its API may change or be removed in a
future release. Using it emits a `cudf_polars.UnstableWarning`; set the
`CUDF_POLARS_WARN_UNSTABLE` environment variable to `1` to have that warning
raised as an error instead. See {doc}`options`.
```

[`LazyFrame.collect`](https://docs.pola.rs/api/python/stable/reference/lazyframe/api/polars.LazyFrame.collect.html)
runs a query on the GPU and then copies the
full result back to host memory as a `pl.DataFrame`. When you want to run
several queries in sequence, or hand a result to another query, that host
round-trip is pure overhead: the data leaves the GPU only to be uploaded again.
Comment thread
madsbk marked this conversation as resolved.
Resolved

`engine.execute()` avoids it. It runs the query and returns a
Comment thread
madsbk marked this conversation as resolved.
Resolved
{class}`~cudf_polars.engine.persisted_result.PersistedQueryResult` whose
partitions stay GPU-resident in the process that produced them. You can then
chain further work through {meth}`~cudf_polars.engine.persisted_result.PersistedQueryResult.lazy`
without a host copy in between.
Comment thread
madsbk marked this conversation as resolved.
Resolved

It is available on the streaming engines:
{class}`~cudf_polars.engine.spmd.SPMDEngine`,
{class}`~cudf_polars.engine.ray.RayEngine`, and
{class}`~cudf_polars.engine.dask.DaskEngine`.

```{note}
This is distinct from Polars' own `LazyFrame.execute()`, which you call directly
on the frame (`df.execute()`) rather than on a cudf-polars engine. cudf-polars
does not accelerate `LazyFrame.execute()` yet: calling it always moves the data
back to the client and host memory, just like
[`LazyFrame.collect`](https://docs.pola.rs/api/python/stable/reference/lazyframe/api/polars.LazyFrame.collect.html).
To keep results GPU-resident, use `engine.execute()` as described here.
```

## Basic usage

```python
import polars as pl
from cudf_polars.engine.ray import RayEngine

with RayEngine() as engine:
# Runs on the GPU, the result stays there (no host copy).
Comment thread
madsbk marked this conversation as resolved.
Resolved
result = engine.execute(
pl.scan_parquet("/data/dataset/*.parquet")
.filter(pl.col("amount") > 100)
.group_by("customer_id")
.agg(pl.col("amount").sum())
)

# Chain more work off the persisted result, still on the GPU.
Comment thread
madsbk marked this conversation as resolved.
Resolved
df = (
result.lazy()
.sort("amount")
.head(10)
.collect(engine=engine)
)
```

The `LazyFrame` returned by `result.lazy()` can be collected **only** with the
engine that produced it, never with a different engine. The partitions never
leave their owning processes, so the default (host) Polars engine cannot read
them, and collecting or executing the result with any other engine is unsupported.
Comment thread
madsbk marked this conversation as resolved.
Resolved

## Chaining into another `execute()`

`result.lazy()` is an ordinary `LazyFrame`, so you can feed it (or further work

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.

Note, it's not really an ordinary LazyFrame because you can't collect it on the CPU, 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.

good point, updated to:

`result.lazy()` supports the usual `LazyFrame` API, so you can add further
operations and pass the resulting query directly to `engine.execute()` without
collecting it first.

Only materialization is special. Like any persisted result, it must run on the
engine that produced it, as described above, and cannot be collected directly
on the host. The query executes on the GPU, and its output remains there as a
new persisted result. This makes it useful for building multi-step pipelines
without transferring intermediate results to host memory:

chained onto it) straight back into `engine.execute()` instead of collecting.
The query runs on the GPU and its output stays there as a new persisted result,
which is handy for building up a multi-step pipeline without ever touching host
memory:

```python
with RayEngine() as engine:
a = engine.execute(pl.scan_parquet("/data/*.parquet"))

# Run more GPU work and keep the result on the GPU (no host copy).
b = engine.execute(a.lazy().filter(pl.col("amount") > 100))

# Collect only when you actually need the data on the host.
df = b.lazy().collect(engine=engine)
```

Each `execute()`/`collect()` consumes the result it reads (move-on-read), so
`a` is spent by the second `execute()` above and cannot be read again.
Comment thread
madsbk marked this conversation as resolved.
Resolved

## Results are one-shot

A persisted result can only be collected once. Attempting to collect the same
`LazyFrame` twice, or to use it in an operation that reads it multiple times
(such as a self-join), raises a `RuntimeError`. Call `engine.execute()` again
Comment on lines +94 to +95

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 is bad (the self-join thing). I guess the problem is that Polar's common subplan elimination doesn't see that these are the same thing twice?

@madsbk madsbk Jul 15, 2026 •

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.

Yes, CSE will sometimes collapse the duplicate scan, so a self-join can happen to work, but not in the general case. Support for repeated reads is tracked in #23115.

to produce a fresh result.

```python
with RayEngine() as engine:
result = engine.execute(pl.scan_parquet("/data/*.parquet"))
lazy = result.lazy()

df = lazy.collect(engine=engine) # OK: consumes the partitions.
df = lazy.collect(engine=engine) # RuntimeError: already consumed.

# Need it again? Re-run the query for a fresh result.
df = engine.execute(pl.scan_parquet("/data/*.parquet")).lazy().collect(engine=engine)
Comment thread
madsbk marked this conversation as resolved.
Resolved
```

## Releasing partitions

Persisted partitions occupy GPU memory until they are released. If you never
collect a result, its partitions are freed when the result (and any `LazyFrame`
derived from it) is garbage-collected. To free them deterministically, use the
context-manager protocol or call
{meth}`~cudf_polars.engine.persisted_result.PersistedQueryResult.release`:

```python
with RayEngine() as engine:
with engine.execute(pl.scan_parquet("/data/*.parquet")) as result:
df = result.lazy().select("a").collect(engine=engine)
# Partitions are released here on scope exit.
```

## SPMD note

On {class}`~cudf_polars.engine.spmd.SPMDEngine`, `execute()` is collective:
every rank must call it with an equivalent query, and each rank's result holds
that rank's own partition (see
[Query symmetry requirement](spmd_engine.md#query-symmetry-requirement)).
4 changes: 3 additions & 1 deletion docs/cudf/source/cudf_polars/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ with RayEngine() as engine:

See {doc}`usage` for the full tutorial, {doc}`engines` for a conceptual overview of the
available engines, {doc}`options` for the
{class}`~cudf_polars.engine.options.StreamingOptions` configuration, and
{class}`~cudf_polars.engine.options.StreamingOptions` configuration,
{doc}`execute` for keeping query results GPU-resident across chained queries, and
{doc}`memory_errors` for guidance on out-of-memory errors and memory tuning.

## Benchmark
Expand Down Expand Up @@ -107,6 +108,7 @@ To learn more, visit the [GPU Support page](https://docs.pola.rs/user-guide/gpu-
usage
engines
options
execute
io_plugins
profiling
other_engines
Expand Down
16 changes: 3 additions & 13 deletions python/cudf_polars/cudf_polars/callback.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,22 +363,12 @@ def execute_with_cudf(
with nvtx.annotate(message="ConvertIR", domain=CUDF_POLARS_NVTX_DOMAIN):
translator = Translator(nt, config)
ir = translator.translate_ir()
ir_translation_errors = translator.errors
if timer is not None:
timer.store(start, time.monotonic_ns(), "gpu-ir-translation")

if len(ir_translation_errors):
# TODO: Display these errors in user-friendly way.
# tracked in https://github.com/rapidsai/cudf/issues/17051
unique_errors = sorted(set(ir_translation_errors), key=str)
formatted_errors = "\n".join(
f"- {e.__class__.__name__}: {e}" for e in unique_errors
)
error_message = (
"Query execution with GPU not possible: unsupported operations."
f"\nThe errors were:\n{formatted_errors}"
)
exception = NotImplementedError(error_message, unique_errors)
exception = translator.unsupported_operations_error()
if exception is not None:
error_message = exception.args[0]
if bool(int(os.environ.get("POLARS_VERBOSE", "0"))):
warnings.warn(error_message, PerformanceWarning, stacklevel=2)
if translator.config_options.raise_on_fail:
Expand Down
24 changes: 24 additions & 0 deletions python/cudf_polars/cudf_polars/dsl/translate.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,30 @@ def translate_ir(self, *, n: int | None = None) -> ir.IR:

return result

def unsupported_operations_error(self) -> NotImplementedError | None:
"""
Build an error describing unsupported operations during translation.

Returns
-------
A `NotImplementedError` whose message (``args[0]``) is safe to surface
to users and whose second argument contains the deduplicated underlying
errors, or ``None`` if no translation errors were recorded.
"""
if not self.errors:
return None
unique_errors = sorted({str(e): e for e in self.errors}.values(), key=str)
# TODO: Display these errors in user-friendly way, tracked in
# https://github.com/rapidsai/cudf/issues/17051
formatted_errors = "\n".join(
f"- {e.__class__.__name__}: {e}" for e in unique_errors
)
message = (
"Query execution with GPU not possible: unsupported operations."
f"\nThe errors were:\n{formatted_errors}"
)
return NotImplementedError(message, unique_errors)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

def translate_expr(self, *, n: int, schema: Schema) -> expr.Expr:
"""
Translate a polars-internal expression IR into our representation.
Expand Down
82 changes: 77 additions & 5 deletions python/cudf_polars/cudf_polars/engine/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import polars as pl

import pylibcudf as plc
from cudf_streaming.table_chunk import TableChunk
from rapidsmpf.coll import AllGather
from rapidsmpf.config import Options, get_environment_variables
Expand Down Expand Up @@ -56,6 +57,7 @@
import cudf_polars.quent
import cudf_polars.quent._logging
from cudf_polars.dsl.ir import IR
from cudf_polars.dsl.translate import Translator
from cudf_polars.quent._context import LocalQuentContext
from cudf_polars.streaming.base import PartitionInfo
from cudf_polars.streaming.parallel import ConfigOptions
Expand Down Expand Up @@ -430,7 +432,7 @@ def execute_ir_on_rank(
config_options: ConfigOptions[StreamingExecutor],
stats: StatsCollector,
collective_id_map: dict[IR, list[int]],
) -> tuple[pl.DataFrame, list[ChannelMetadata]]:
) -> tuple[DataFrame, list[ChannelMetadata]]:
"""
Execute a Polars IR query on a single rank's GPU.

Expand Down Expand Up @@ -460,7 +462,7 @@ def execute_ir_on_rank(
Returns
-------
result
This rank's output fragment as a Polars DataFrame.
This rank's output fragment as a GPU-resident :class:`~cudf_polars.containers.DataFrame`.
Comment thread
madsbk marked this conversation as resolved.
Resolved
metadata
Collected channel metadata.
"""
Expand Down Expand Up @@ -521,7 +523,7 @@ def execute_ir_on_rank(
list(ir.schema.values()),
stream,
)
return df.to_polars(), metadata_collector
return df, metadata_collector


_RESERVED_EXECUTOR_KEYS: frozenset[str] = frozenset(
Expand Down Expand Up @@ -662,7 +664,7 @@ def evaluate_on_rank(
collect_metadata: bool = False,
local_quent_context: LocalQuentContext | None = None,
query_id: uuid.UUID,
) -> tuple[pl.DataFrame, list[ChannelMetadata]]:
) -> tuple[DataFrame, list[ChannelMetadata]]:
"""
Evaluate a polars IR plan on a single rank.

Expand Down Expand Up @@ -697,7 +699,7 @@ def evaluate_on_rank(
Returns
-------
result
This rank's output fragment as a Polars DataFrame.
This rank's output fragment as a GPU-resident :class:`~cudf_polars.containers.DataFrame`.
metadata
Collected channel metadata.
"""
Expand Down Expand Up @@ -764,3 +766,73 @@ def evaluate_on_rank(
stats,
collective_id_map,
)


def is_duplicated_output(metadata: list[ChannelMetadata] | None) -> bool:
"""
Return whether a query's output is duplicated across ranks.

A duplicated output is an identical, complete copy held on every rank (for
example the result of a global sort/limit), signalled by the ``duplicated``
channel flag on the final output.

Parameters
----------
metadata
Channel metadata for the query.

Returns
-------
``True`` if the output is an identical copy held on every rank.
"""
return bool(metadata and metadata[-1].duplicated)


def drop_if_replicated(
df: DataFrame, rank: int, metadata: list[ChannelMetadata] | None
) -> DataFrame:
"""
Drop a duplicated output on non-root ranks.

Parameters
----------
df
This rank's output partition.
rank
This rank's index within the cluster.
metadata
Channel metadata for the query.

Returns
-------
``df`` or a freshly-allocated empty same-schema frame.
"""
if rank != 0 and is_duplicated_output(metadata):
return DataFrame.from_table(
plc.copying.empty_like(df.table, stream=df.stream),
df.column_names,
df.dtypes,
df.stream,
num_rows=0,
)
return df


def raise_for_translation_errors(translator: Translator) -> None:
"""
Raise if the translator recorded unsupported operations.

Parameters
----------
translator
The translator whose :attr:`~cudf_polars.dsl.translate.Translator.errors`
are checked.

Raises
------
NotImplementedError
If the query contains operations unsupported on the GPU.
"""
error = translator.unsupported_operations_error()
if error is not None:
raise error
Loading
Loading