Skip to content

Commit bcd0d68

Browse files
cromwellianRaycodexalxmrsclaude
authored
Reuse gradient plans and reduce Dataset registration overhead (#301)
🛠️ Codex Repeated training calls can prepare a SQL grad/VJP/JVP statement once with `Context.prepare` and write new Dataset values into existing input buffers. Fine-chunk registration counts partitions arithmetically and registers Arrow batches directly; extension handles retain Dataset metadata and invalidation state. `Context(threads=...)` exposes target parallel partitions. This independently useful change starts the NanoGPT optimization stack; shared/compact execution, resident training and the evidence report follow separately. Apple M5 Ultra measurements: one-cell-chunk registration 31.372→0.405 ms (77.44× for that specific case), update-and-sum 2.769→1.027 ms (2.70×), repeated-CTE preparation 1.709→1.307 ms (1.31×). Tiny-model warm time improved 1.11×, but its five-step total regressed due to setup; this does not claim universally faster startup. Validation: 47 focused AD/preparation tests passed, covering current inputs, changing join-key ranges, old-result snapshots, coordinate rejection and shared Context invalidation. The complete downstream stack passed 714 non-integration tests. Changed Python files pass Ruff. Review order: this PR → #302 (shared kernels) → #303 (compact arrays) → #305 (resident training). #304 contains the separate consolidated report and evidence. Closes #294 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Prepared queries now support gradient, vector-Jacobian product, and Jacobian-vector product operations, including repeated execution after registered table data is updated or re-registered. * Added an option to configure the number of query threads. * Added support for creating contexts with extensions. * **Bug Fixes** * Improved prepared-query results when join-key values change and when datasets are registered in smaller chunks. * Improved in-memory partitioning for datasets. * **Documentation** * Clarified that prepared queries retain programs for repeated execution. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Ray <cromwellian@Rays-Mac-Studio.local> Co-authored-by: GPT-6 <noreply@openai.com> Co-authored-by: Alex Merose <al@merose.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent d22a5ff commit bcd0d68

5 files changed

Lines changed: 274 additions & 35 deletions

File tree

‎tests/test_ad.py‎

Lines changed: 44 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -136,9 +136,47 @@ def test_a_mention_in_a_literal_is_not_a_call():
136136
assert rows == [{"s": "grad(x)", "jvp(v)": 1}]
137137

138138

139-
def test_prepare_refuses_a_gradient(problem):
140-
ctx, *_ = problem
141-
with pytest.raises(NotImplementedError, match="grad"):
142-
ctx.prepare(
143-
f"WITH {LOSS} SELECT feature, grad(loss, w) AS g FROM weights"
144-
)
139+
def test_context_prepare_runs_gradient_steps_and_reads_writes(problem):
140+
ctx, x, w, y = problem
141+
step = ctx.prepare(
142+
f"WITH {LOSS} SELECT feature, grad(loss, w) AS w FROM weights ORDER BY feature"
143+
)
144+
old = step()
145+
original = old["w"].to_numpy().copy()
146+
replacement = xr.Dataset(
147+
{"w": ("feature", w.copy() * 2)}, coords={"feature": np.arange(3)}
148+
)
149+
got = step(weights=replacement)
150+
np.testing.assert_allclose(
151+
got["w"], 2 * x.T @ (x @ replacement.w.values - y)
152+
)
153+
np.testing.assert_array_equal(old["w"], original)
154+
with pytest.raises(ValueError, match="coordinates"):
155+
step(weights=replacement.assign_coords(feature=[3, 4, 5]))
156+
# A table registered again under its name, with the same columns.
157+
ctx.deregister_table("weights")
158+
ctx.from_dataset("weights", replacement * 2)
159+
np.testing.assert_allclose(
160+
step()["w"], 2 * x.T @ (x @ (2 * replacement.w.values) - y)
161+
)
162+
163+
164+
def test_prepared_gradient_writes_only_the_tables_it_reads(problem):
165+
ctx, x, w, y = problem
166+
other = xr.Dataset(
167+
{"w": ("feature", w.copy())}, coords={"feature": np.arange(3)}
168+
)
169+
ctx.from_dataset("w", other)
170+
step = ctx.prepare(
171+
f"WITH {LOSS} SELECT feature, grad(loss, w) AS w FROM weights ORDER BY feature"
172+
)
173+
with pytest.raises(ValueError, match="reads no Dataset registered as 'w'"):
174+
step(w=other * 2)
175+
np.testing.assert_array_equal(
176+
ctx.sql("SELECT feature, w FROM w ORDER BY feature").to_dataset()["w"],
177+
w,
178+
)
179+
# The loss reads the targets, so a call may write them.
180+
want = 2 * x.T @ (x @ w + y)
181+
targets = xr.Dataset({"y": ("sample", -y)}, coords={"sample": np.arange(6)})
182+
np.testing.assert_allclose(step(targets=targets)["w"], want)

‎tests/test_prepare.py‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,11 @@
99

1010
from xarray_sql import Context
1111

12+
try:
13+
from einfold.datafusion import EinFold
14+
except ImportError:
15+
EinFold = None
16+
1217
# The build side of the join, `a`, is what a reused hash join would keep.
1318
JOIN = """
1419
SELECT b.i, SUM(t.v2 * b.w) AS s
@@ -17,6 +22,26 @@
1722
"""
1823

1924

25+
@pytest.mark.parametrize("extension", [False, True])
26+
def test_join_key_data_columns_can_change_their_range(extension):
27+
ctx = Context()
28+
if extension:
29+
if EinFold is None:
30+
pytest.skip("requires the optional EinFold planner")
31+
ctx = ctx.with_extensions(EinFold())
32+
a = xr.Dataset({"key": ("i", np.arange(128)), "v": ("i", np.ones(128))})
33+
b = xr.Dataset({"key": ("j", np.arange(256)), "w": ("j", np.arange(256.0))})
34+
ctx.from_dataset("a", a)
35+
ctx.from_dataset("b", b)
36+
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"
37+
query = ctx.prepare(sql)
38+
for start in (0, 128, 16):
39+
updated = a.copy(deep=True)
40+
updated["key"][:] = np.arange(start, start + 128)
41+
rows = query(a=updated)
42+
assert rows.equals(ctx.sql(sql).to_arrow_table())
43+
44+
2045
def _a(v):
2146
return xr.Dataset(
2247
{"v": (("i", "j"), v)},
@@ -262,3 +287,61 @@ def test_a_quoted_table_replaced_in_sql_counts_too():
262287
ctx.sql('CREATE OR REPLACE TABLE "Mixed" AS VALUES (1), (2)').collect()
263288
with pytest.raises(ValueError, match="registered again"):
264289
query()
290+
291+
292+
def test_extension_handle_keeps_dataset_metadata_and_invalidation(ctx):
293+
want = ctx.sql("SELECT * FROM a").to_dataset()
294+
derived = ctx.with_extensions()
295+
query = derived.prepare("SELECT i, j, v FROM a ORDER BY i, j")
296+
xr.testing.assert_identical(
297+
derived.sql("SELECT * FROM a").to_dataset(), want
298+
)
299+
ctx.deregister_table("a")
300+
with pytest.raises(ValueError, match="registered again"):
301+
query()
302+
303+
304+
@pytest.mark.parametrize(
305+
"chunks", [{"i": 1, "j": 1}, {"i": 1}, {"i": 4, "j": 5}]
306+
)
307+
def test_fine_chunk_registration_keeps_rows_metadata_and_writes(chunks):
308+
values = np.arange(129 * 33, dtype=np.float64).reshape(129, 33)
309+
ds = _a(values)
310+
ds.attrs["experiment"] = "fine chunks"
311+
ctx = Context()
312+
ctx.from_dataset("a", ds, chunks=chunks)
313+
sql = "SELECT i,j,v FROM a ORDER BY i,j"
314+
xr.testing.assert_identical(ctx.sql(sql).to_dataset(), ds)
315+
run = ctx.prepare(sql)
316+
replacement = ds * 2
317+
rows = run(a=replacement)
318+
np.testing.assert_array_equal(rows["v"], replacement.v.values.reshape(-1))
319+
320+
321+
@pytest.mark.parametrize("threads", [1, 60])
322+
def test_thread_target_is_explicit_and_keeps_xarray_support(threads):
323+
ctx = Context(threads=threads)
324+
assert ctx.sql(
325+
"SELECT value FROM information_schema.df_settings "
326+
"WHERE name='datafusion.execution.target_partitions'"
327+
).to_pylist() == [{"value": str(threads)}]
328+
ctx.from_dataset("a", _a(np.ones((4, 3))))
329+
assert ctx.prepare("SELECT SUM(v) AS s FROM a")().to_pylist() == [
330+
{"s": 12.0}
331+
]
332+
333+
334+
def test_thread_target_leaves_the_given_config_unchanged():
335+
config = (
336+
SessionConfig().with_information_schema(True).with_target_partitions(7)
337+
)
338+
Context(config, threads=2)
339+
assert Context(config).sql(
340+
"SELECT value FROM information_schema.df_settings "
341+
"WHERE name='datafusion.execution.target_partitions'"
342+
).to_pylist() == [{"value": "7"}]
343+
344+
345+
def test_thread_target_must_be_positive():
346+
with pytest.raises(ValueError, match="positive"):
347+
Context(threads=0)

‎xarray_sql/ad.py‎

Lines changed: 66 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,9 @@
4343
4444
[sql_all][xarray_sql.ad.sql_all] runs several statements that take
4545
``grad`` of the same loss for the price of one backward pass, which is
46-
how a training step updates each of a model's parameter tables. For the
46+
how a training step updates each of a model's parameter tables.
47+
[Context.prepare][xarray_sql.Context.prepare] keeps ddx's programs for a
48+
statement that calls them, to run it again on every step. For the
4749
programs underneath (``grad``, ``vjp``, ``jvp`` and ``run``, to build a
4850
backward pass once and run it every step), use ``ddxdb.ad`` directly;
4951
they take a ``Context`` like any other ``SessionContext``.
@@ -52,9 +54,13 @@
5254
from __future__ import annotations
5355

5456
import re
55-
from collections.abc import Sequence
57+
import threading
58+
from collections.abc import Callable, Sequence
5659

57-
from datafusion import SessionContext
60+
import ddxdb
61+
import pyarrow as pa
62+
from datafusion import DataFrame, SessionContext
63+
from datafusion.plan import LogicalPlan
5864
from ddxdb import ad as _ddx
5965

6066
__all__ = ["STOP_GRADIENT", "calls_ad", "register", "sql", "sql_all"]
@@ -138,3 +144,60 @@ def sql_all(ctx: SessionContext, statements: Sequence[str]) -> list:
138144
frames: list = _ddx.sql_all(ctx, list(statements))
139145
wrap = getattr(ctx, "_wrap", None)
140146
return [wrap(f) for f in frames] if wrap else frames
147+
148+
149+
class _RecordingBackend(_ddx.DataFusionBackend):
150+
"""ddx's DataFusion backend, keeping the plan of each query ddx
151+
differentiates."""
152+
153+
def __init__(self, ctx: SessionContext):
154+
super().__init__(ctx)
155+
self.plans: list[LogicalPlan] = []
156+
157+
def plan_sql(self, sql: str) -> bytes:
158+
self.plans.append(SessionContext.sql(self.ctx, sql).logical_plan())
159+
plan: bytes = super().plan_sql(sql)
160+
return plan
161+
162+
163+
def _prepare(
164+
ctx: SessionContext, statement: str
165+
) -> tuple[Callable[[Callable[[], None]], pa.Table], list[LogicalPlan]]:
166+
"""``statement``, with the programs of its ``grad``, ``vjp`` and ``jvp``
167+
calls kept to run it again. Calling the result with a function that
168+
writes the tables' new values calls it, then returns the rows.
169+
170+
Preparing runs the statement once, which builds the programs. That run
171+
also gives the logical plans of what the statement reads: the queries
172+
ddx differentiates, and the statement once its calls are rewritten.
173+
174+
Between calls, a table may change its rows or be registered again under
175+
its name, but must keep its columns and their types; a view must keep
176+
its definition.
177+
"""
178+
backend = _RecordingBackend(ctx)
179+
prepared = ddxdb.Prepared(backend, [statement], "datafusion")
180+
# Calls wait for each other, since each writes the same tables.
181+
lock = threading.Lock()
182+
183+
def run() -> DataFrame:
184+
with prepared.run() as rewritten:
185+
# SessionContext's own sql, as ddx's sql_all does: the tables
186+
# ddx wrote leave the catalog once the statement is planned.
187+
(frame,) = [
188+
SessionContext.sql(ctx, s) for s in rewritten.statements
189+
]
190+
return frame
191+
192+
# The first run is what plans the queries ddx differentiates.
193+
statement_plan = run().logical_plan()
194+
plans = [*backend.plans, statement_plan]
195+
196+
def rows(write: Callable[[], None]) -> pa.Table:
197+
# One lock from the writes until the rows are read, so another call
198+
# can't change the tables in between.
199+
with lock:
200+
write()
201+
return run().to_arrow_table()
202+
203+
return rows, plans

‎xarray_sql/reader.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from __future__ import annotations
1212

1313
import itertools
14+
import math
1415
import os
1516
import sys
1617
from collections.abc import Callable, Iterable, Iterator
@@ -21,9 +22,9 @@
2122
import xarray as xr
2223

2324
from .df import (
25+
DEFAULT_BATCH_SIZE,
2426
Block,
2527
Chunks,
26-
DEFAULT_BATCH_SIZE,
2728
_block_len,
2829
_block_metadata,
2930
_block_slices_from_resolved,
@@ -296,11 +297,10 @@ def _in_memory_partitions(
296297
# isn't contiguous in memory, and flattening it would copy. More
297298
# partitions than cores only adds overhead, since an in-memory table has
298299
# no partitions to prune.
300+
# Count the Cartesian chunk grid without constructing slices that this
301+
# in-memory path never reads, even for very finely chunked inputs.
299302
count = min(
300-
sum(
301-
1
302-
for _ in _block_slices_from_resolved(ds, resolve_chunks(ds, chunks))
303-
),
303+
math.prod(len(axis) for axis in resolve_chunks(ds, chunks).values()),
304304
os.cpu_count() or 1,
305305
)
306306
# `per_partition` batches of `size` rows each make `count` partitions,
@@ -324,7 +324,7 @@ def read_xarray_table(
324324
_iteration_callback: (
325325
Callable[[Block, list[str] | None], None] | None
326326
) = None,
327-
) -> "LazyArrowStreamTable":
327+
) -> LazyArrowStreamTable:
328328
"""Create a lazy DataFusion table from an xarray Dataset.
329329
330330
This is the simplest way to register xarray data with DataFusion.

0 commit comments

Comments
 (0)