Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
50 changes: 44 additions & 6 deletions tests/test_ad.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
83 changes: 83 additions & 0 deletions tests/test_prepare.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)},
Expand Down Expand Up @@ -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)
69 changes: 66 additions & 3 deletions xarray_sql/ad.py
Original file line number Diff line number Diff line change
Expand Up @@ -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``.
Expand All @@ -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"]
Expand Down Expand Up @@ -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
12 changes: 6 additions & 6 deletions xarray_sql/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from __future__ import annotations

import itertools
import math
import os
import sys
from collections.abc import Callable, Iterable, Iterator
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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.
Expand Down
Loading
Loading