Skip to content

datadeps: give a wrapper and its parent their own slots over one shared copy - #840

Merged
jpsamaroo merged 9 commits into
masterfrom
jps/datadeps-wrapper-slots
Nov 30, 2026
Merged

jpsamaroo merged 9 commits into
masterfrom
jps/datadeps-wrapper-slots

Conversation

@jpsamaroo

Copy link
Copy Markdown
Member

The symptom

On plain Distributed with two CPU workers, Datadeps gives a wrapped array (transpose(A), adjoint(A), and a few others) and its parent the wrong slots. Writes land in the wrong place and reads see stale or wrongly shaped data, with no error:

using Distributed; addprocs(1)
@everywhere using Dagger, LinearAlgebra
A = reshape(collect(1.0:9.0), 3, 3)
Dagger.spawn_datadeps() do
    Dagger.@spawn scope=Dagger.scope(worker=2) size(In(transpose(A)))
    Dagger.@spawn scope=Dagger.scope(worker=2) (x->(x[1,2] += 10; nothing))(InOut(A))
end
A[1,2], A[2,1]   # master: (4.0, 12.0) -- the write landed in A[2,1]; expected (14.0, 2.0)

If the order is reversed, the transpose task receives the plain Matrix and reads values from before the write. If a GPU task writes A after a host task reads transpose(A), the copy fails with "Scalar indexing is disallowed".

Wrappers checked on master (both orders, a remote writer and reader, writes through either side):

Wrapper master this PR
transpose(A), adjoint(A) (real and complex) wrong slot type, transposed writes, stale reads fixed
PermutedDimsArray(A, (2,1)), reshape(view(A, ...), n), transpose(view(A, ...)) stale reads, "Spans only partially match" assertions fixed
view(A, ...), UpperTriangular(A) correct correct
reshape(A::Array, n) wrong shape or BoundsError not fixed (see below)
Symmetric(A), Hermitian(A) assertions or stale reads not fixed (see below)

The cause

Datadeps keeps one copy of each piece of memory per memory space. Its aliased-object cache keys those copies by aliasing (the memory an argument touches). move_rewrap splits known wrappers (SubArray, the triangular types) into a parent plus a header, caches only the parent, and rebuilds the wrapper around the cached copy. Three separate places assumed that one aliasing key means one argument, and a wrapper that shares its parent's aliasing breaks each of them:

  1. Transpose and Adjoint were not registered with move_rewrap. So they were cached as whole objects. Their aliasing is exactly their parent's, so transpose(A) and A shared one cache entry, and whichever reached a worker first became the other's slot.
  2. The in-place slot path returned the cache's value. If an argument is already in the destination space, it is its own slot. generate_slot! still looked it up in the cache and used what came back. That could be the other argument's object, so a copy out of the origin read a Matrix into a Transpose slot and the data arrived transposed.
  3. Arguments with equal aliasing were never linked. populate_ainfo! links a new argument to every argument it overlaps, so a write through one shows up in the other's history. It only does this when the aliasing is new, though: the overlap search skips equal ainfos. So transpose(A) had no history of the write to A, was "refreshed" from its stale origin, and overwrote that write.

PermutedDimsArray and ReshapedArray fail the other way round. Their aliasing comes from the generic struct fallback, so it differs from the parent's key, and as whole objects each got a private copy of the parent's memory on the worker. That copy is separate from the parent's own slot there, and the dependency tracking cannot keep the two in sync.

The fix

One commit per cause:

  • Link equal-aliasing arguments (populate_ainfo!). When an ainfo is already known, link the new argument to the arguments of every overlapping ainfo, its own included, and merge their history once per pair. This only runs when a different argument has already registered the same aliasing, so the usual case (one argument per piece of memory) is unchanged.
  • An in-place slot is the argument itself (generate_slot!). The in-place path now always returns the argument itself. It records only leaves in the cache, because the cache must hold only the leaves that move_rewrap rebuilds wrappers around. The decision depends only on the chunktype, so it is the same on every MPI rank. A wrapper also no longer makes the aliasing query that registering it used to require, which is a collective under MPI.
  • Transpose/Adjoint become move_rewrap wrappers (parent as the only child, no header), like the triangular types. Remainder copies forward through them to the parent.
  • PermutedDimsArray/ReshapedArray become wrappers too. The permutation is a type parameter, so it needs no header. A reshape's shape is a value, so it is sent as a broadcast header, the same way SubArray sends its indices.

The Distributed and MPI paths share the move_rewrap protocol, so both get the wrapper changes, and every new decision depends only on types.

Not fixed here

  • reshape(A::Array, n) together with A. These are two separate Arrays over the same memory, with the same aliasing but different shapes, so there is no wrapper to rebuild. The cache cannot tell them apart without shape information on every cache hit, and under MPI getting that would mean a collective on a common path.
  • Symmetric/Hermitian. Their aliasing covers the whole parent, but copyto! between two of them copies only the stored triangle. Fixing them needs either a triangle-shaped aliasing or a whole-parent move!. The latter runs into the GPU move! ambiguities described in AGENTS.md lesson 16.

Tests

  • test/datadeps.jl, "Wrappers share their parent's slot". Short read/write sequences on a remote worker for Transpose, Adjoint (real and complex), PermutedDimsArray, ReshapedArray, a transpose of a view, and SubArray as a control. Each sequence runs under both planners and covers both orders, writes through either side, a local read after a remote write, and a partial (remainder) write. Every read and the final array are compared with running the same sequence serially. Master: 90 pass, 72 fail, 30 error. This PR: 252/252.
  • test/gpu.jl, "Datadeps wrapper and parent with a GPU task" (each backend in GPU_SCOPES). Host data with a device writer and host or device readers of transpose(A). Run against CUDA (RTX 5060, Julia 1.11): errors on master with scalar indexing, 8/8 here.
  • test/mpi/cpu.jl, "Cross-rank wrapper dataflow". The same idea across MPI ranks, through the MPIWireValue move_rewrap path.

Suite runs on this branch:

Julia 1.12, 3 workers, run from a copy of this branch with an env whose Dagger is developed from it.

  • --test datadeps: 1785 pass, 2 broken (the existing ones).
  • --test allocations: 24/24.
  • --test array/linalg/core, matmul, cholesky, lu, --test array/permute, memory-spaces, mutation: all pass (1883, 682, 74, 136, 32, 22, 71).
  • MPI CPU, test/mpi/run.jl 2 2 test/mpi/cpu.jl: 1147 and 1182 pass on the two ranks. The new MPI testset run alone gives 13 failures and 2 errors on master (the same transposed write) and 32/32 here.
  • CUDA (RTX 5060, Julia 1.11): only the new test/gpu.jl testset and a probe of the same cases were run, not the whole GPU suite.

Possible merge conflicts

#833, #834 and #839 also touch aliased_object! and nearby code in src/datadeps/aliasing.jl. This PR is based on master and leaves aliased_object! itself alone. It changes populate_ainfo!, the in-place branch of generate_slot!, and the move_rewrap registrations.

Interaction with #839: this was found while working on #839 ("datadeps: never free the user's own object at region end"), whose review reproduced it. #839's built-in trigger (a host task reads In(transpose(X)) and a device task writes InOut(X) for a CuArray X, after which X was freed at region end) also passes with this PR alone. The in-place path no longer records the Transpose in the cache, so X's memory is first recorded in its own device space. #839's guard is still needed for its second trigger (a user-defined processor whose move returns its input), and the two changes do not overlap.

AGENTS.md gains lesson 103, numbered to avoid collisions with other open PRs.

🤖 Generated with Claude Code

https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr

jpsamaroo and others added 9 commits November 28, 2026 20:41
`populate_ainfo!` links a new argument to every argument it overlaps, so a
write through one records history on the other. But it only does so when the
argument's aliasing is new: the overlap search skips equal ainfos, and the
whole block is skipped when the ainfo is already known. Two *distinct*
arguments with exactly the same aliasing (`transpose(A)` and `A`, or
`reshape(A, n)` and `A`) were therefore never linked.

The second one then had no history and its owner was still its origin, so
when a task on worker 2 wrote `InOut(A)` and a later task on worker 2 read
`In(transpose(A))`, the read was preceded by a full copy from the stale
origin into the shared slot, overwriting the write: the reader saw the old
values and the write was lost on copy-back.

Link the new argument to every argument of every ainfo overlapping the
known one, itself included, merging their history once per pair. This only
runs when a different argument has already registered the same ainfo, so
the common path (one argument per memory) is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr
When an argument already lives in the destination space, `generate_slot!`
skips `move_rewrap` and uses the argument as its own slot. It still routed
the argument through `aliased_object!` to record it in the aliased-object
cache, but then used whatever that call returned -- which, on a cache hit, is
the object some *other* argument registered for the same aliasing key.

A `Transpose` has exactly its parent's aliasing, so the origin-space slot of
`transpose(A)` could come back as `A` itself. Copies out of the origin then
read the `Matrix` into a destination `Transpose` (or vice versa), and the
data arrived transposed: a region reading `In(transpose(A))` and then
writing `InOut(A)` on worker 2 wrote `A[2,1]` instead of `A[1,2]`.

Use the argument itself as the slot, as the comment above already says, and
register only leaves: `move_rewrap` caches only leaves and rebuilds wrappers
around them, so a wrapper registered here could be handed out as a later
argument's *parent* copy. The decision is by type (`chunktype`), so it is
uniform across MPI ranks, and a wrapper now skips the (collective) aliasing
query that registering it used to make.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr
Datadeps shares one copy of each piece of memory per memory space through
its aliased-object cache, keyed by aliasing. `move_rewrap` decomposes known
wrappers (`SubArray`, the triangular types) and caches only the leaf, then
rebuilds each wrapper around the shared leaf copy. `Transpose` and `Adjoint`
were not registered, so they were cached as leaves -- and because their
aliasing is exactly their parent's, a wrapper and its parent shared one
cache entry. Whichever reached a space first became the slot of the other:
a task asking for `InOut(A)` on worker 2 after one reading
`In(transpose(A))` received a `Transpose` (its `x[1,2] += 10` landed in
`A[2,1]`), and in the other order the transpose task received the plain
`Matrix`.

Register both with the `move_rewrap` header/children protocol (no header,
the parent as the only child), like the triangular wrappers, so each
argument gets a slot of its own type around the one shared parent copy.
The protocol is shared by the Distributed and MPI paths and the decision is
type-level, so it stays rank-uniform. The result type comes from
`promote_op` rather than `{eltype(PT),PT}`, since a transpose's eltype is
the transposed element type for nested arrays.

Remainder (partial) copies also forward through both wrappers to their
parent, as they already do for `SubArray` and the triangular types; without
that, a remainder copy into a transposed slot hit `find_object_holding_ptr`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr
Neither has an `aliasing` method of its own; the generic struct fallback
describes each by its parent's memory. But `move_rewrap` treated them as
leaves and moved them whole, so in a destination space each got a *private*
copy of its parent's memory, separate from the parent's own slot there.
Dependency tracking assumes one copy of any memory per space, so the two
copies silently diverged: after a remote `InOut(A)`, a remote read of
`PermutedDimsArray(A, (2, 1))` saw the old values, and other orders failed
span assertions ("Spans only partially match") during remainder copies.

Register both with the `move_rewrap` protocol so they share the parent's
copy, as `Transpose`/`Adjoint` now do. `PermutedDimsArray`'s permutation is
a type parameter, so it needs no header; a `ReshapedArray`'s shape is a
value, so it travels as a broadcast header (the `SubArray` mode). Remainder
copies forward through both to their parent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr
Regression tests for the wrapper-slot fixes. `test/datadeps.jl` runs short
read/write sequences on a remote worker through a wrapper and its parent --
both orders, writes through either side, a local reader after a remote
writer, and a partial (remainder) write -- for `Transpose`, `Adjoint` (real
and complex), `PermutedDimsArray`, `ReshapedArray`, a transpose of a view,
and `SubArray` as a control, under both planners. Every read and the final
array are compared with running the same sequence serially. On master, 72
of the 192 checks fail and 30 error; all 252 pass now.

`test/gpu.jl` covers host data with a device task in the same region, per
backend in `GPU_SCOPES`: on master, a host read of `transpose(A)` followed
by a device write of `A` fails with scalar indexing, and the other orders
read stale data. Run against CUDA (RTX 5060, Julia 1.11): errors on master,
8/8 pass with the fixes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr
…its leaf

Records the three places that assumed one argument per aliasing key, the
opposite failure of generic-struct wrappers, the two wrappers this does not
fix (`reshape(::Array)` and `Symmetric`/`Hermitian`), and how to test it.
Numbered 103 to avoid colliding with lessons in other open PRs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr
Mirrors the Distributed "Wrappers share their parent's slot" testset through
the MPIWireValue `move_rewrap` path: `Transpose`, `Adjoint`,
`PermutedDimsArray` and `ReshapedArray` read and written across ranks, with
rank 0 checking the write-backs and every read against a serial run. On
master (2 ranks x 2 threads) 13 checks fail and 2 error, including the
transposed write (`A[2,1]` instead of `A[1,2]`); the full CPU MPI suite
passes here (1147 and 1182 on the two ranks).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TRNkMLrH1mZo3YmkaHP8Jr
Review finding 1 on PR #840 (blocker): Linking equal-aliasing arguments makes a DSparseArray used next to transpose(D) or view(D) fail with an AssertionError, including an order that worked on master
Requested: Fix before merge: a whole-object container and a wrapper of it in one region must work in both orders, with the wrapper still treated as aliasing the whole object (e.g. skip the new equal-aliasing linking for whole-object aliasing, or source that copy from the latest history entry); add a test for both orders.

Use the latest overlapping history entry to choose the source space and
transfer the aliasing root so a narrow view cannot mark untouched parts
of its parent current. Cover both access orders for transpose and view,
with either the parent or wrapper writing, on Distributed and MPI.

The focused Distributed tests pass all 32 assertions under both
planners. On Julia 1.12.6, minimum driver allocations after ten warmup
regions and GC before each of five samples were 4,908 to 5,010
(246,744 to 251,720 bytes) for a remotely written sparse container and
4,858 to 5,032 (241,320 to 249,624 bytes) for the dense matrix control.

Written by an AI agent on jpsamaroo's review feedback.
Keep the master ownership tests and the wrapper dataflow tests. Number
the wrapper lesson after the new master lessons.

Written by an AI agent on jpsamaroo's review feedback.
@github-actions

Copy link
Copy Markdown
Contributor

Dagger benchmarks: dirty vs master

Counts are benchmark metrics (time, allocations, bytes). Timing changes require non-overlapping median ± IQR bands; both revisions need at least five timed samples, and timing regressions need an independent confirmation run.

Backend Regressions Improvements Within noise Inconclusive time Suites
Threads 0 3 18 0 4/4
Distributed 0 0 1 0 4/4
Distributed+Threads 1 0 0 0 4/4
MPI 0 0 1 0 4/4
MPI+Threads 0 1 17 2 4/4
Total 1 4 37 2 20/20

Regressions across all backends

Backend Benchmark Metric Change
Distributed+Threads array/dagger/N=1024 (block 512)/alloc (rand) time +164.7%

Improvements across all backends

Backend Benchmark Metric Change
MPI+Threads array/dagger/N=256 (block 128)/broadcast (X .+ 1) time -68.6%
Threads stencil/dagger/N=256 (block 128)/neighbors (Clamp) time -61.7%
Threads stencil/dagger/N=1024 (block 512)/multi-expr time -58.5%
Threads array/dagger/N=1024 (block 512)/transpose (permutedims) time -34.7%
Threads (1 process × 4 threads) — 0 regressions, 3 improvements
Suite Regressions Improvements Within noise Inconclusive time
array 0 1 9 0
linalg 0 0 3 0
sparse 0 0 0 0
stencil 0 2 6 0

Improvements

Benchmark Metric Change
stencil/dagger/N=256 (block 128)/neighbors (Clamp) time -61.7%
stencil/dagger/N=1024 (block 512)/multi-expr time -58.5%
array/dagger/N=1024 (block 512)/transpose (permutedims) time -34.7%

Within noise

Benchmark Metric Change
stencil/dagger/N=256 (block 128)/alloc (neighbors Wrap) time +271.7%
array/dagger/N=1024 (block 512)/reduce (sum) time +77.9%
array/dagger/N=256 (block 256)/add (X + X) time +61.2%
array/dagger/N=256 (block 128)/norm time +46.9%
stencil/dagger/N=1024 (block 512)/neighbors (Reflect) time +39.6%
linalg/dagger/N=256 (block 128)/matvec (A*x) time +38.8%
stencil/dagger/N=1024 (block 512)/neighbors (Pad) time +34.7%
array/dagger/N=1024 (block 512)/norm time +32.6%
array/dagger/N=1024 (block 128)/alloc (rand) time +32.1%
array/dagger/N=256 (block 128)/broadcast (X .+ 1) time +31.4%
stencil/dagger/N=1024 (block 128)/alloc (neighbors Wrap) time +28.5%
array/dagger/N=256 (block 128)/add (X + X) time +26.0%
linalg/dagger/N=256 (block 128)/solve (A\b via lu) time +25.2%
array/dagger/N=1024 (block 128)/transpose (permutedims) time +25.2%
linalg/dagger/N=256 (block 128)/matmul (A*A) time -26.8%
stencil/dagger/N=256 (block 128)/neighbors (Reflect) time -42.3%
array/dagger/N=1024 (block 512)/alloc (rand) time -53.7%
stencil/dagger/N=256 (block 128)/assign (const) time -55.9%
Distributed (4 processes × 1 thread) — 0 regressions, 0 improvements
Suite Regressions Improvements Within noise Inconclusive time
array 0 0 1 0
linalg 0 0 0 0
sparse 0 0 0 0
stencil 0 0 0 0

Within noise

Benchmark Metric Change
array/dagger/N=1024 (block 512)/reduce (sum) time +35.7%
Distributed+Threads (2 processes × 2 threads) — 1 regressions, 0 improvements
Suite Regressions Improvements Within noise Inconclusive time
array 1 0 0 0
linalg 0 0 0 0
sparse 0 0 0 0
stencil 0 0 0 0

Regressions

Benchmark Metric Change
array/dagger/N=1024 (block 512)/alloc (rand) time +164.7%
MPI (4 ranks × 1 thread) — 0 regressions, 0 improvements
Suite Regressions Improvements Within noise Inconclusive time
array 0 0 1 0
linalg 0 0 0 0
sparse 0 0 0 0
stencil 0 0 0 0

Within noise

Benchmark Metric Change
array/dagger/N=1024 (block 128)/transpose (permutedims) time -49.0%
MPI+Threads (2 ranks × 2 threads) — 0 regressions, 1 improvements
Suite Regressions Improvements Within noise Inconclusive time
array 0 1 10 0
linalg 0 0 2 0
sparse 0 0 0 0
stencil 0 0 5 2

Improvements

Benchmark Metric Change
array/dagger/N=256 (block 128)/broadcast (X .+ 1) time -68.6%

Within noise

Benchmark Metric Change
stencil/dagger/N=1024 (block 512)/update (+) time +132.6%
stencil/dagger/N=256 (block 128)/assign (const) time +101.6%
stencil/dagger/N=256 (block 128)/update (+) time +97.7%
array/dagger/N=256 (block 128)/reduce (sum) time +84.2%
stencil/dagger/N=1024 (block 128)/neighbors (Pad) time +80.9%
array/dagger/N=256 (block 128)/alloc (rand) time +72.9%
array/dagger/N=1024 (block 512)/transpose (permutedims) time +70.3%
linalg/dagger/N=256 (block 256)/cholesky time +58.5%
array/dagger/N=256 (block 256)/broadcast (X .+ 1) time +50.4%
array/dagger/N=256 (block 256)/reduce (sum) time +37.4%
array/dagger/N=256 (block 256)/add (X + X) time +36.1%
array/dagger/N=1024 (block 512)/norm time -37.8%
array/dagger/N=256 (block 128)/transpose (permutedims) time -42.7%
linalg/dagger/N=256 (block 128)/matvec (A*x) time -44.7%
stencil/dagger/N=1024 (block 512)/assign (const) time -45.6%
array/dagger/N=256 (block 128)/norm time -60.8%
array/dagger/N=256 (block 128)/add (X + X) time -64.9%

Inconclusive timing changes

Benchmark Metric Change
stencil/dagger/N=256 (block 128)/neighbors (Clamp) time +77.8%
stencil/dagger/N=256 (block 256)/neighbors (Clamp) time +48.4%

Full results and plots (download the benchmark-results-* artifacts).

@jpsamaroo
jpsamaroo merged commit 7d5c9bf into master Nov 30, 2026
54 of 62 checks passed
@jpsamaroo
jpsamaroo deleted the jps/datadeps-wrapper-slots branch November 30, 2026 01:05
jpsamaroo added a commit to AnnaLena77/Dagger_AL.jl that referenced this pull request Nov 30, 2026
Keep the regression tests for identity-less copy ownership and lifetime
alongside the wrapper and sparse-container tests added by JuliaParallel#840.

Written by an AI agent on jpsamaroo's review feedback.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant