diff --git a/tests/test_ad.py b/tests/test_ad.py index 0f868bc7..dadbe764 100644 --- a/tests/test_ad.py +++ b/tests/test_ad.py @@ -136,9 +136,47 @@ def test_a_mention_in_a_literal_is_not_a_call(): assert rows == [{"s": "grad(x)", "jvp(v)": 1}] -def test_prepare_refuses_a_gradient(problem): - ctx, *_ = problem - with pytest.raises(NotImplementedError, match="grad"): - ctx.prepare( - f"WITH {LOSS} SELECT feature, grad(loss, w) AS g FROM weights" - ) +def test_context_prepare_runs_gradient_steps_and_reads_writes(problem): + ctx, x, w, y = problem + step = ctx.prepare( + f"WITH {LOSS} SELECT feature, grad(loss, w) AS w FROM weights ORDER BY feature" + ) + old = step() + original = old["w"].to_numpy().copy() + replacement = xr.Dataset( + {"w": ("feature", w.copy() * 2)}, coords={"feature": np.arange(3)} + ) + got = step(weights=replacement) + np.testing.assert_allclose( + got["w"], 2 * x.T @ (x @ replacement.w.values - y) + ) + np.testing.assert_array_equal(old["w"], original) + with pytest.raises(ValueError, match="coordinates"): + step(weights=replacement.assign_coords(feature=[3, 4, 5])) + # A table registered again under its name, with the same columns. + ctx.deregister_table("weights") + ctx.from_dataset("weights", replacement * 2) + np.testing.assert_allclose( + step()["w"], 2 * x.T @ (x @ (2 * replacement.w.values) - y) + ) + + +def test_prepared_gradient_writes_only_the_tables_it_reads(problem): + ctx, x, w, y = problem + other = xr.Dataset( + {"w": ("feature", w.copy())}, coords={"feature": np.arange(3)} + ) + ctx.from_dataset("w", other) + step = ctx.prepare( + f"WITH {LOSS} SELECT feature, grad(loss, w) AS w FROM weights ORDER BY feature" + ) + with pytest.raises(ValueError, match="reads no Dataset registered as 'w'"): + step(w=other * 2) + np.testing.assert_array_equal( + ctx.sql("SELECT feature, w FROM w ORDER BY feature").to_dataset()["w"], + w, + ) + # The loss reads the targets, so a call may write them. + want = 2 * x.T @ (x @ w + y) + targets = xr.Dataset({"y": ("sample", -y)}, coords={"sample": np.arange(6)}) + np.testing.assert_allclose(step(targets=targets)["w"], want) diff --git a/tests/test_prepare.py b/tests/test_prepare.py index 8cc356bc..935c044f 100644 --- a/tests/test_prepare.py +++ b/tests/test_prepare.py @@ -9,6 +9,11 @@ from xarray_sql import Context +try: + from einfold.datafusion import EinFold +except ImportError: + EinFold = None + # The build side of the join, `a`, is what a reused hash join would keep. JOIN = """ SELECT b.i, SUM(t.v2 * b.w) AS s @@ -17,6 +22,26 @@ """ +@pytest.mark.parametrize("extension", [False, True]) +def test_join_key_data_columns_can_change_their_range(extension): + ctx = Context() + if extension: + if EinFold is None: + pytest.skip("requires the optional EinFold planner") + ctx = ctx.with_extensions(EinFold()) + a = xr.Dataset({"key": ("i", np.arange(128)), "v": ("i", np.ones(128))}) + b = xr.Dataset({"key": ("j", np.arange(256)), "w": ("j", np.arange(256.0))}) + ctx.from_dataset("a", a) + ctx.from_dataset("b", b) + sql = "SELECT a.i,b.j,a.v+b.w AS s FROM a JOIN b ON a.key=b.key ORDER BY a.i,b.j" + query = ctx.prepare(sql) + for start in (0, 128, 16): + updated = a.copy(deep=True) + updated["key"][:] = np.arange(start, start + 128) + rows = query(a=updated) + assert rows.equals(ctx.sql(sql).to_arrow_table()) + + def _a(v): return xr.Dataset( {"v": (("i", "j"), v)}, @@ -262,3 +287,61 @@ def test_a_quoted_table_replaced_in_sql_counts_too(): ctx.sql('CREATE OR REPLACE TABLE "Mixed" AS VALUES (1), (2)').collect() with pytest.raises(ValueError, match="registered again"): query() + + +def test_extension_handle_keeps_dataset_metadata_and_invalidation(ctx): + want = ctx.sql("SELECT * FROM a").to_dataset() + derived = ctx.with_extensions() + query = derived.prepare("SELECT i, j, v FROM a ORDER BY i, j") + xr.testing.assert_identical( + derived.sql("SELECT * FROM a").to_dataset(), want + ) + ctx.deregister_table("a") + with pytest.raises(ValueError, match="registered again"): + query() + + +@pytest.mark.parametrize( + "chunks", [{"i": 1, "j": 1}, {"i": 1}, {"i": 4, "j": 5}] +) +def test_fine_chunk_registration_keeps_rows_metadata_and_writes(chunks): + values = np.arange(129 * 33, dtype=np.float64).reshape(129, 33) + ds = _a(values) + ds.attrs["experiment"] = "fine chunks" + ctx = Context() + ctx.from_dataset("a", ds, chunks=chunks) + sql = "SELECT i,j,v FROM a ORDER BY i,j" + xr.testing.assert_identical(ctx.sql(sql).to_dataset(), ds) + run = ctx.prepare(sql) + replacement = ds * 2 + rows = run(a=replacement) + np.testing.assert_array_equal(rows["v"], replacement.v.values.reshape(-1)) + + +@pytest.mark.parametrize("threads", [1, 60]) +def test_thread_target_is_explicit_and_keeps_xarray_support(threads): + ctx = Context(threads=threads) + assert ctx.sql( + "SELECT value FROM information_schema.df_settings " + "WHERE name='datafusion.execution.target_partitions'" + ).to_pylist() == [{"value": str(threads)}] + ctx.from_dataset("a", _a(np.ones((4, 3)))) + assert ctx.prepare("SELECT SUM(v) AS s FROM a")().to_pylist() == [ + {"s": 12.0} + ] + + +def test_thread_target_leaves_the_given_config_unchanged(): + config = ( + SessionConfig().with_information_schema(True).with_target_partitions(7) + ) + Context(config, threads=2) + assert Context(config).sql( + "SELECT value FROM information_schema.df_settings " + "WHERE name='datafusion.execution.target_partitions'" + ).to_pylist() == [{"value": "7"}] + + +def test_thread_target_must_be_positive(): + with pytest.raises(ValueError, match="positive"): + Context(threads=0) diff --git a/xarray_sql/ad.py b/xarray_sql/ad.py index d0ff2c8f..371f178f 100644 --- a/xarray_sql/ad.py +++ b/xarray_sql/ad.py @@ -43,7 +43,9 @@ [sql_all][xarray_sql.ad.sql_all] runs several statements that take ``grad`` of the same loss for the price of one backward pass, which is -how a training step updates each of a model's parameter tables. For the +how a training step updates each of a model's parameter tables. +[Context.prepare][xarray_sql.Context.prepare] keeps ddx's programs for a +statement that calls them, to run it again on every step. For the programs underneath (``grad``, ``vjp``, ``jvp`` and ``run``, to build a backward pass once and run it every step), use ``ddxdb.ad`` directly; they take a ``Context`` like any other ``SessionContext``. @@ -52,9 +54,13 @@ from __future__ import annotations import re -from collections.abc import Sequence +import threading +from collections.abc import Callable, Sequence -from datafusion import SessionContext +import ddxdb +import pyarrow as pa +from datafusion import DataFrame, SessionContext +from datafusion.plan import LogicalPlan from ddxdb import ad as _ddx __all__ = ["STOP_GRADIENT", "calls_ad", "register", "sql", "sql_all"] @@ -138,3 +144,60 @@ def sql_all(ctx: SessionContext, statements: Sequence[str]) -> list: frames: list = _ddx.sql_all(ctx, list(statements)) wrap = getattr(ctx, "_wrap", None) return [wrap(f) for f in frames] if wrap else frames + + +class _RecordingBackend(_ddx.DataFusionBackend): + """ddx's DataFusion backend, keeping the plan of each query ddx + differentiates.""" + + def __init__(self, ctx: SessionContext): + super().__init__(ctx) + self.plans: list[LogicalPlan] = [] + + def plan_sql(self, sql: str) -> bytes: + self.plans.append(SessionContext.sql(self.ctx, sql).logical_plan()) + plan: bytes = super().plan_sql(sql) + return plan + + +def _prepare( + ctx: SessionContext, statement: str +) -> tuple[Callable[[Callable[[], None]], pa.Table], list[LogicalPlan]]: + """``statement``, with the programs of its ``grad``, ``vjp`` and ``jvp`` + calls kept to run it again. Calling the result with a function that + writes the tables' new values calls it, then returns the rows. + + Preparing runs the statement once, which builds the programs. That run + also gives the logical plans of what the statement reads: the queries + ddx differentiates, and the statement once its calls are rewritten. + + Between calls, a table may change its rows or be registered again under + its name, but must keep its columns and their types; a view must keep + its definition. + """ + backend = _RecordingBackend(ctx) + prepared = ddxdb.Prepared(backend, [statement], "datafusion") + # Calls wait for each other, since each writes the same tables. + lock = threading.Lock() + + def run() -> DataFrame: + with prepared.run() as rewritten: + # SessionContext's own sql, as ddx's sql_all does: the tables + # ddx wrote leave the catalog once the statement is planned. + (frame,) = [ + SessionContext.sql(ctx, s) for s in rewritten.statements + ] + return frame + + # The first run is what plans the queries ddx differentiates. + statement_plan = run().logical_plan() + plans = [*backend.plans, statement_plan] + + def rows(write: Callable[[], None]) -> pa.Table: + # One lock from the writes until the rows are read, so another call + # can't change the tables in between. + with lock: + write() + return run().to_arrow_table() + + return rows, plans diff --git a/xarray_sql/reader.py b/xarray_sql/reader.py index 8ec88bcf..db7c82c9 100644 --- a/xarray_sql/reader.py +++ b/xarray_sql/reader.py @@ -11,6 +11,7 @@ from __future__ import annotations import itertools +import math import os import sys from collections.abc import Callable, Iterable, Iterator @@ -21,9 +22,9 @@ import xarray as xr from .df import ( + DEFAULT_BATCH_SIZE, Block, Chunks, - DEFAULT_BATCH_SIZE, _block_len, _block_metadata, _block_slices_from_resolved, @@ -296,11 +297,10 @@ def _in_memory_partitions( # isn't contiguous in memory, and flattening it would copy. More # partitions than cores only adds overhead, since an in-memory table has # no partitions to prune. + # Count the Cartesian chunk grid without constructing slices that this + # in-memory path never reads, even for very finely chunked inputs. count = min( - sum( - 1 - for _ in _block_slices_from_resolved(ds, resolve_chunks(ds, chunks)) - ), + math.prod(len(axis) for axis in resolve_chunks(ds, chunks).values()), os.cpu_count() or 1, ) # `per_partition` batches of `size` rows each make `count` partitions, @@ -324,7 +324,7 @@ def read_xarray_table( _iteration_callback: ( Callable[[Block, list[str] | None], None] | None ) = None, -) -> "LazyArrowStreamTable": +) -> LazyArrowStreamTable: """Create a lazy DataFusion table from an xarray Dataset. This is the simplest way to register xarray data with DataFusion. diff --git a/xarray_sql/sql.py b/xarray_sql/sql.py index f64166a4..8b238502 100644 --- a/xarray_sql/sql.py +++ b/xarray_sql/sql.py @@ -1,6 +1,9 @@ +import copy import re import time import uuid +from collections.abc import Callable +from types import ModuleType import numpy as np import pyarrow as pa @@ -9,7 +12,6 @@ from datafusion.catalog import Schema from datafusion.expr import TableScan from datafusion.plan import ExecutionPlan, LogicalPlan -from types import ModuleType from . import cftime as cft from .df import ( @@ -43,9 +45,20 @@ class Context(SessionContext): """A datafusion `SessionContext` that also supports `xarray.Dataset`s. Also available under its original name, ``XarrayContext``. + ``threads=`` sets DataFusion's target parallel partitions, overriding + that setting in an explicit ``config``. The default is the CPU count. + It is a concurrency target, rather than a fixed number of OS threads. """ - def __init__(self, config: SessionConfig | None = None, *args, **kwargs): + def __init__( + self, + config: SessionConfig | None = None, + *args, + threads: int | None = None, + **kwargs, + ): + if threads is not None and threads < 1: + raise ValueError("threads must be positive") if config is None: # Split a query's work across partitions only where enough rows # reach it, by DataFusion's estimate. DataFusion otherwise splits @@ -65,6 +78,12 @@ def __init__(self, config: SessionConfig | None = None, *args, **kwargs): "true", ) ) + if threads is not None: + # SessionConfig's with_ methods set the setting on the config + # they're called on, so set it on a copy: the caller's config is + # theirs to use again. The copy shares the Rust config, which + # with_target_partitions replaces rather than changes. + config = copy.copy(config).with_target_partitions(threads) super().__init__(config, *args, **kwargs) # Track registered xarray Datasets so XarrayDataFrame can recover # defaults (dimension_columns) and metadata (var/dataset attrs, @@ -87,6 +106,20 @@ def __init__(self, config: SessionConfig | None = None, *args, **kwargs): if _ad is not None: _ad.register(self) + def with_extensions(self, *extensions) -> "Context": + """Install DataFusion extension bundles, retaining xarray support. + + Returns another handle on the same session, with this Context's + Dataset metadata and prepared-query invalidation state shared. + Extension codecs belong to the returned handle, so use it for + subsequent queries, as with DataFusion's own method. + """ + session = super().with_extensions(*extensions) + derived = object.__new__(type(self)) + derived.__dict__.update(self.__dict__) + derived.ctx = session.ctx + return derived + def from_dataset( self, name: str, @@ -214,9 +247,13 @@ def _from_dataset( table = read_xarray_table( input_table, chunks, coord_arrays=coord_arrays ) + register(table_name, table) + elif schema is None: + # Uniform Datasets can register their shared Arrow buffers + # directly, without a temporary catalog entry and lookup. + self.register_record_batches(table_name, partitions) else: - table = self._in_memory_table(partitions) - register(table_name, table) + register(table_name, self._in_memory_table(partitions)) self._maybe_register_cftime_udf(input_table) return self @@ -314,8 +351,10 @@ def prepare(self, query: str) -> "PreparedQuery": for weights in trajectory: # Datasets shaped like w's rows = step(w=weights) - See [PreparedQuery][xarray_sql.PreparedQuery] for what a call - can write. + A query that calls ``grad``, ``vjp`` or ``jvp`` keeps the programs + ddx builds for them instead. See + [PreparedQuery][xarray_sql.PreparedQuery] for what a call can + write. Args: query: A SQL query string. @@ -323,17 +362,7 @@ def prepare(self, query: str) -> "PreparedQuery": Returns: A [PreparedQuery][xarray_sql.PreparedQuery]; call it to run the query. - - Raises: - NotImplementedError: If the query calls ``grad``, ``vjp`` or - ``jvp``, which only ``sql()`` computes for now. """ - if _ad is not None and _ad.calls_ad(query): - # TODO(#294): prepare the query's programs with ddx. - raise NotImplementedError( - "prepare() doesn't compute grad, vjp or jvp yet; run the " - "query with sql(), or several with xarray_sql.ad.sql_all()" - ) return PreparedQuery(self, query) def _write(self, writes: dict[str, xr.Dataset]) -> None: @@ -415,10 +444,27 @@ class PreparedQuery: query again. A call raises if a table the query reads has been registered again since it was prepared. Functions such as ``now()`` are evaluated once, when the query is prepared. + + A query that calls ``grad``, ``vjp`` or ``jvp`` keeps the programs ddx + builds for those calls, rather than a plan. Preparing it runs it once, + to build them and to find the tables it reads. A table it reads may also + be registered again under the same name, with the same columns and types. + A view it reads must keep its definition; prepare the query again after + changing one. """ def __init__(self, ctx: Context, query: str): self._ctx = ctx + self._gradient: Callable[[Callable[[], None]], pa.Table] | None = None + if _ad is not None and _ad.calls_ad(query): + self._gradient, plans = _ad._prepare(ctx, query) + # A call may write any Dataset the query reads, which leaves out + # the tables ddx wrote. It finds each by name, so one registered + # again is written too. + self._writable = set().union(*map(_tables_read, plans)) & set( + ctx._registered_datasets + ) + return start = time.perf_counter() df = SessionContext.sql(ctx, query) plan = df.execution_plan() @@ -442,9 +488,11 @@ def __init__(self, ctx: Context, query: str): # A plan keeps state from a run (a hash join keeps the table it # built), so each call runs a fresh copy of it, decoded from its # serialized form. Copying a plan copies its in-memory tables, so - # over large ones it's slower than planning again; a plan that reads - # a lazy table, or is nested deeper than protobuf decodes, can't be - # copied at all. Either way, each call plans the query again. + # over large ones it's slower than planning again. A plan that reads + # a lazy table, has an extension's nodes, or is nested deeper than + # protobuf decodes can't be copied at all: DataFusion's own codec + # serializes it, since an extension's codec may keep state from a + # run. Either way, each call plans the query again. self._plan: ExecutionPlan | None = None start = time.perf_counter() try: @@ -464,12 +512,17 @@ def __call__(self, **tables: xr.Dataset) -> pa.Table: Returns: The query's rows. """ + writable = ( + self._registered if self._gradient is None else self._writable + ) for name in tables: - if name not in self._registered: + if name not in writable: raise ValueError( f"the query reads no Dataset registered as {name!r} " "when it was prepared" ) + if self._gradient is not None: + return self._gradient(lambda: self._ctx._write(tables)) for name, deregistrations in self._read.items(): if self._ctx._deregistrations.get(name, 0) != deregistrations: raise ValueError( @@ -495,6 +548,8 @@ def _copy(ctx: SessionContext, plan: ExecutionPlan) -> ExecutionPlan: # TODO(#283): reset the plan's state with datafusion-python's binding of # reset_plan_states, once it has one, rather than decode it again. # `plan` itself never runs, so it has no state to leave behind. + # TODO(xqlsystems/einfold#159): serialize with the session's codecs + # too, once EinFold's copies read their tables' current values. return ExecutionPlan.from_bytes(ctx, plan.to_bytes())