diff --git a/AGENTS.md b/AGENTS.md index 00d880fe3..ad8c5740e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1182,9 +1182,38 @@ this section verbatim). Each entry is one bullet starting with `- `. seen, so a region using both `transpose(X)` and `X` registers `X`'s memory as a host original, and the device slot for `X` -- `X` itself -- was recorded as a Datadeps copy and freed at region end. The same key sharing - also hands one argument the other's slot, which is still open: a task + also handed one argument the other's slot before lesson 108's fix: a task asking for `InOut(A)` on another worker, after one reading - `In(transpose(A))`, receives a `Transpose`, and its write lands + `In(transpose(A))`, received a `Transpose`, and its write landed transposed in `A`. Never assume one object has one key in one space, and never assume a slot `f` returns is not the user's own object; check `slot_holds_value` before recording it for freeing. + +108. **A wrapper reaches the aliased-object cache only through its leaf, and + two arguments can share one aliasing exactly.** `transpose(A)`'s + `aliasing` *is* `A`'s, and three places assumed one argument per aliasing + key. `move_rewrap` cached unregistered wrappers as leaves, so `Transpose` + and `A` shared a cache entry and one received the other's slot: a remote + `InOut(A)` after `In(transpose(A))` got a `Transpose`, and its + `x[1,2] += 10` landed in `A[2,1]`. `generate_slot!`'s in-place path + returned the cache's value rather than the argument, so a copy's + origin-space source could be the *other* argument, and the data arrived + transposed. And `populate_ainfo!` links arguments only when an ainfo is + new, so a second argument with an *equal* ainfo had no history and was + "refreshed" from its stale origin over a write. Wrappers that use the + generic struct `aliasing` (`PermutedDimsArray`, `ReshapedArray`) fail the + opposite way: their key differs from the parent's, so as leaves each got + a private copy of the parent's memory in a space that must hold only one. + Any wrapper whose memory is its parent's needs the `move_rewrap` protocol + and remainder forwarding; the cache holds only leaves. For a whole-object + container such as `DSparseArray`, use the latest overlapping history entry + to find the source space. Copy the aliasing root itself: a view's copy + would update only part of the destination while marking the entire + container current. Two gaps remain: + `reshape(A::Array, n)` is a second *leaf* over `A`'s memory with a + different shape, which the cache cannot tell apart without per-hit shape + information (a collective under MPI); and `Symmetric`/`Hermitian` claim + the whole parent while `copyto!` between them copies one triangle, so + the protocol alone is not enough for them. Test with a remote reader + *and* a remote writer, in both orders: in one process every slot is the + argument itself, so none of this is visible. diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index eb132d27f..f867b1cc5 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -1706,7 +1706,8 @@ function move!(dep_mod, to_space::MPIMemorySpace, from_space::MPIMemorySpace, to # source handle's tag outside of task context tag = Dagger.in_task() ? to_tag() : to_tag(from.handle) @dagdebug nothing :mpi "[$local_rank][$tag] Moving from $(from_space.rank) to $(to_space.rank)\n" - if dep_mod === identity + # A whole-object wrapper transports its aliasing root as a full value. + if dep_mod === identity || dep_mod === Dagger.aliasing_root # Below the crossover, handle+ack overhead makes host staging # competitive; each side checks its own (equal-sized) buffer local_nbytes = local_rank == from_space.rank ? from.handle.size : @@ -1723,15 +1724,16 @@ function move!(dep_mod, to_space::MPIMemorySpace, from_space::MPIMemorySpace, to end # Full copy: receive directly into the destination buffer when possible elseif local_rank == from_space.rank - send_yield!(poolget(from.handle; uniform=false), to_space.comm, to_space.rank, tag) + from_val = dep_mod(poolget(from.handle; uniform=false)) + send_yield!(from_val, to_space.comm, to_space.rank, tag) elseif local_rank == to_space.rank - to_val = poolget(to.handle; uniform=false) + to_val = dep_mod(poolget(to.handle; uniform=false)) val, inplace = recv_yield!(to_val, from_space.comm, from_space.rank, tag) if !inplace # Dense payloads may arrive host-staged; materialize in # dest storage so inner move! sees matching spaces val = mpi_localize(to_space.innerSpace, val) - move!(dep_mod, to_space.innerSpace, from_space.innerSpace, to_val, val) + move!(identity, to_space.innerSpace, from_space.innerSpace, to_val, val) end end else diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index 3fd0cda8c..47767e7a8 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -1094,6 +1094,27 @@ function populate_ainfo!(state::DataDepsState, original_arg_w::ArgumentWrapper, # Initialize owner and readers state.ainfos_owner[target_ainfo] = nothing state.ainfos_readers[target_ainfo] = Pair{DTask,Int}[] + else + # The ainfo is already known, but `original_arg_w` may not be: a + # *different* argument with exactly this aliasing registered it + # (`transpose(A)` and `A`, or `reshape(A, n)` and `A`). The overlap + # search above never sees that argument, since it skips equal ainfos, + # so without this the two would not be linked: a write through one + # would leave no history on the other, which would then be "refreshed" + # from its stale origin, overwriting the write. Link this argument to + # every argument of every ainfo overlapping this one, itself included. + for other_ainfo in state.ainfos_overlaps[target_ainfo] + for other_remote_arg_w in state.ainfo_arg[other_ainfo] + other_arg = state.remote_arg_to_original[other_remote_arg_w.arg] + other_arg_w = ArgumentWrapper(other_arg, other_remote_arg_w.dep_mod) + other_arg_w == original_arg_w && continue + if !(other_arg_w in state.arg_overlaps[original_arg_w]) + push!(state.arg_overlaps[original_arg_w], other_arg_w) + push!(state.arg_overlaps[other_arg_w], original_arg_w) + merge_history!(state, original_arg_w, other_arg_w) + end + end + end end end function merge_history!(state::DataDepsState, arg_w::ArgumentWrapper, other_arg_w::ArgumentWrapper) @@ -1488,10 +1509,20 @@ function generate_slot!(state::DataDepsState, dest_space, data) # Nothing to move: the slot for data already in `dest_space` is the data # itself. Going through `move_rewrap` here would allocate a second Chunk # (and DRef) over the very same memory, which costs a MemPool round-trip - # per argument per region and buys nothing. Still route through + # per argument per region and buys nothing. Still route a leaf through # `aliased_object!` so the cache records this object as the (never-freed) # original for its aliasing key, exactly as the general path does. - aliased_object!(Returns(data), aliased_object_cache, data)::Chunk + # + # N.B. The slot is `data` itself, never the cache's value: another + # argument with the same aliasing key may have registered a different + # object for it (a `Transpose`'s key is its parent's). And only a leaf + # may be registered, because `move_rewrap` caches only leaves and + # rebuilds wrappers around them; a wrapper registered here would be + # handed out as some later argument's parent copy. + if move_rewrap_child_types(chunktype(data)) === nothing + aliased_object!(Returns(data), aliased_object_cache, data)::Chunk + end + data else moved = with(DATADEPS_THUNK_ID=>tid) do remotecall_endpoint_toplevel(move_rewrap, current_acceleration(), aliased_object_cache, from_proc, to_proc, orig_space, dest_space, data) @@ -1613,6 +1644,47 @@ for wrapper in (UpperTriangular, LowerTriangular, UnitUpperTriangular, UnitLower end end +# Transpose/Adjoint: parent payload, empty header. These must not be leaves: +# their `aliasing` *is* their parent's, so as leaves a wrapper and its parent +# shared one aliased-object cache key, and whichever reached a space first +# became the other's slot (a `Transpose` handed to a task asking for the +# `Matrix`, or vice versa). As wrappers, only the parent is cached, and each +# argument gets its own wrapper rebuilt around the shared copy. +for wrapper in (Transpose, Adjoint) + @eval begin + move_rewrap_parts(x::$wrapper) = ((parent(x),), nothing) + move_rewrap_build(::Type{<:$wrapper}, (p,), ::Nothing) = $wrapper(p) + move_rewrap_child_types(::Type{T}) where {T<:$wrapper} = (T.parameters[2],) + # N.B. Not `$wrapper{eltype(PT),PT}`: the wrapper's eltype is the + # transposed/adjointed element type, which differs for nested arrays. + move_rewrap_result_type(::Type{<:$wrapper}, (PT,), ::Nothing) = + Base.promote_op($wrapper, PT) + end +end + +# PermutedDimsArray and ReshapedArray have no `aliasing` method of their own; +# the generic struct fallback describes them by their parent's memory. As +# leaves they were therefore *moved whole*, giving each one a private copy of +# its parent's memory in the destination space, which the dependency tracking +# (which assumes one copy of any memory per space) cannot keep coherent: a +# write through the parent was invisible to the wrapper, and vice versa. As +# wrappers they share the parent's copy. +# +# PermutedDimsArray: the permutation is a type parameter, so no header is needed +move_rewrap_parts(x::PermutedDimsArray) = ((parent(x),), nothing) +move_rewrap_build(::Type{<:PermutedDimsArray{T,N,perm}}, (p,), ::Nothing) where {T,N,perm} = + PermutedDimsArray(p, perm) +move_rewrap_child_types(::Type{T}) where {T<:PermutedDimsArray} = (T.parameters[5],) +move_rewrap_result_type(::Type{<:PermutedDimsArray{T,N,perm,iperm}}, (PT,), ::Nothing) where {T,N,perm,iperm} = + PermutedDimsArray{eltype(PT),N,perm,iperm,PT} +# ReshapedArray: the shape is a value, so it is carried as the header +move_rewrap_parts(x::Base.ReshapedArray) = ((parent(x),), size(x)) +move_rewrap_build(::Type{<:Base.ReshapedArray}, (p,), dims) = reshape(p, dims) +move_rewrap_child_types(::Type{T}) where {T<:Base.ReshapedArray} = (T.parameters[3],) +move_rewrap_header_mode(::Type{<:Base.ReshapedArray}) = :broadcast +move_rewrap_result_type(::Type{<:Base.ReshapedArray}, (PT,), dims) = + Base.promote_op(reshape, PT, typeof(dims)) + # Nested Chunk: unwrap on the owner and recurse move_rewrap(accel, cache::AliasedObjectCache, from_proc::Processor, to_proc::Processor, from_space::MemorySpace, to_space::MemorySpace, data::Chunk) = remotecall_endpoint_toplevel(move_rewrap, accel, cache, from_proc, to_proc, from_space, to_space, data) diff --git a/src/datadeps/hierarchical.jl b/src/datadeps/hierarchical.jl index b195a879e..b58b72497 100644 --- a/src/datadeps/hierarchical.jl +++ b/src/datadeps/hierarchical.jl @@ -1832,7 +1832,7 @@ function _hierarchical_copy_from!(state::DataDepsState, arg_w::ArgumentWrapper, enqueue_remainder_copy_from!(state, origin_space, arg_w, remainder, origin_scope, write_num) elseif remainder isa FullCopy origin_scope = UnionScope(map(ExactScope, collect(processors(origin_space)))...) - enqueue_copy_from!(state, origin_space, arg_w, origin_scope, write_num) + enqueue_copy_from!(state, origin_space, arg_w, remainder, origin_scope, write_num) else @assert remainder isa NoAliasing "Expected NoAliasing, got $(typeof(remainder))" # Emit the same elision event as flat `distribute_tasks!`. Consumers of diff --git a/src/datadeps/queue.jl b/src/datadeps/queue.jl index e22866428..b1702dad3 100644 --- a/src/datadeps/queue.jl +++ b/src/datadeps/queue.jl @@ -185,7 +185,7 @@ function distribute_tasks!(queue::DataDepsTaskQueue) enqueue_remainder_copy_from!(state, origin_space, arg_w, remainder, origin_scope, write_num) elseif remainder isa FullCopy origin_scope = UnionScope(map(ExactScope, collect(processors(origin_space)))...) - enqueue_copy_from!(state, origin_space, arg_w, origin_scope, write_num) + enqueue_copy_from!(state, origin_space, arg_w, remainder, origin_scope, write_num) else @assert remainder isa NoAliasing "Expected NoAliasing, got $(typeof(remainder))" @dagdebug nothing :spawn_datadeps "Skipped copy-from (up-to-date): $origin_space" @@ -378,7 +378,7 @@ function distribute_task!(queue::DataDepsTaskQueue, state::DataDepsState, all_pr if remainder isa MultiRemainderAliasing enqueue_remainder_copy_to!(state, our_space, arg_w, remainder, value(f), idx, our_scope, task, write_num) elseif remainder isa FullCopy - enqueue_copy_to!(state, our_space, arg_w, value(f), idx, our_scope, task, write_num) + enqueue_copy_to!(state, our_space, arg_w, remainder, value(f), idx, our_scope, task, write_num) else @assert remainder isa NoAliasing "Expected NoAliasing, got $(typeof(remainder))" @dagdebug tid :spawn_datadeps "($(repr(value(f))))[$(idx-1)][$dep_mod] Skipped copy-to (up-to-date): $our_space" diff --git a/src/datadeps/remainders.jl b/src/datadeps/remainders.jl index 509da2f8e..8fe467b57 100644 --- a/src/datadeps/remainders.jl +++ b/src/datadeps/remainders.jl @@ -43,8 +43,19 @@ memory_spans(mra::MultiRemainderAliasing) = vcat(memory_spans.(mra.remainders).. Base.hash(mra::MultiRemainderAliasing, h::UInt) = hash(mra.remainders, hash(MultiRemainderAliasing, h)) Base.:(==)(mra1::MultiRemainderAliasing, mra2::MultiRemainderAliasing) = mra1.remainders == mra2.remainders -# A whole-object copy from the argument's recorded owner space. -struct FullCopy end +# An ordinary full copy uses the argument's direct owner and dependency +# modifier. An indivisible object uses the latest writer of its aliasing root. +struct FullCopy{S<:Union{Nothing,MemorySpace}} + whole_object_source::S +end +FullCopy() = FullCopy(nothing) +full_copy_source(state, arg_w, ::FullCopy{Nothing}) = (state.arg_owner[arg_w], arg_w.dep_mod) +function full_copy_source(state, arg_w, copy::FullCopy) + # An explicit modifier may select the whole object from a field of a + # larger argument. Keep that selection for the in-place move. + dep_mod = arg_w.dep_mod === identity ? aliasing_root : arg_w.dep_mod + return copy.whole_object_source, dep_mod +end """ compute_remainder_for_arg!(state::DataDepsState, @@ -115,23 +126,13 @@ function compute_remainder_for_arg!(state::DataDepsState, # memory space -- the whole object is current in exactly one space: the most # recent writer (or the origin owner if never written). There is thus never a # meaningful span "remainder" to compute, so we short-circuit to a whole-object - # `FullCopy` from the owner space (or `NoAliasing` if the target already holds - # it). This avoids the span-diff computation and the construction + transfer of - # a `RemainderAliasing` entirely. We detect this from the aliasing info, which - # is a bare `ObjectAliasing` for such containers (see `aliases_as_whole`). - # - # `arg_owner` is the most-recent *direct* writer of `arg_w`, while the merged - # `arg_history` records the latest write through *any* overlapping argument. - # For every path Datadeps currently exercises a whole-object container is only - # ever reached through a single argument, so these agree -- the assertion below - # guards that invariant. They could only diverge under cross-argument aliasing - # of a whole-object container (the same container written through one argument - # and read through a different, overlapping one); supporting that would require - # sourcing the copy from `history[end].space` instead of `arg_owner`. + # `FullCopy` of the aliasing root. The latest history entry includes writes + # through overlapping wrappers, while `arg_owner` only records direct + # writes to this argument. if aliases_as_whole(aliasing!(state, target_space, arg_w)) history = state.arg_history[arg_w] - @assert isempty(history) || history[end].space == owner_space "whole-object container reached through a different overlapping argument than its owner; cross-argument aliasing of whole-object containers is unsupported" - return owner_space == target_space ? (NoAliasing(), 0) : (FullCopy(), 0) + source_space = isempty(history) ? owner_space : history[end].space + return source_space == target_space ? (NoAliasing(), 0) : (FullCopy(source_space), 0) end spaces_set = Set{MemorySpace}() @@ -471,10 +472,9 @@ function enqueue_remainder_copy_from!(state::DataDepsState, dest_space::MemorySp end # FIXME: Document me -function enqueue_copy_to!(state::DataDepsState, dest_space::MemorySpace, arg_w::ArgumentWrapper, +function enqueue_copy_to!(state::DataDepsState, dest_space::MemorySpace, arg_w::ArgumentWrapper, copy::FullCopy, f, idx, dest_scope, task, write_num::Int) - dep_mod = arg_w.dep_mod - source_space = state.arg_owner[arg_w] + source_space, dep_mod = full_copy_source(state, arg_w, copy) target_ainfo = aliasing!(state, dest_space, arg_w) @dagdebug task.uid :spawn_datadeps "($(repr(f)))[$(idx-1)][$dep_mod] Enqueueing full copy-to for $(typeof(arg_w.arg))[$(arg_w.dep_mod)]: $source_space => $dest_space" @@ -506,10 +506,9 @@ function enqueue_copy_to!(state::DataDepsState, dest_space::MemorySpace, arg_w:: add_reader!(state, arg_w, source_space, source_ainfo, copy_task, write_num) add_writer!(state, arg_w, dest_space, target_ainfo, copy_task, write_num; copied=true) end -function enqueue_copy_from!(state::DataDepsState, dest_space::MemorySpace, arg_w::ArgumentWrapper, +function enqueue_copy_from!(state::DataDepsState, dest_space::MemorySpace, arg_w::ArgumentWrapper, copy::FullCopy, dest_scope, write_num::Int) - dep_mod = arg_w.dep_mod - source_space = state.arg_owner[arg_w] + source_space, dep_mod = full_copy_source(state, arg_w, copy) target_ainfo = aliasing!(state, dest_space, arg_w) @dagdebug nothing :spawn_datadeps "($(typeof(arg_w.arg)))[$dep_mod] Enqueueing full copy-from: $source_space => $dest_space" @@ -675,8 +674,9 @@ function write_remainder!(copies::Vector{UInt8}, copies_offset::UInt64, to, to_p return write_remainder!(copies, copies_offset, real_to, to_ptr, n) end -# Remainder copies for common objects -for wrapper in (UpperTriangular, LowerTriangular, UnitUpperTriangular, UnitLowerTriangular, SubArray) +# Remainder copies for common objects: each wrapper's spans lie in its parent +for wrapper in (UpperTriangular, LowerTriangular, UnitUpperTriangular, UnitLowerTriangular, SubArray, + Transpose, Adjoint, PermutedDimsArray, Base.ReshapedArray) @eval function read_remainder!(copies::Vector{UInt8}, copies_offset::UInt64, from::$wrapper, from_ptr::UInt64, n::UInt64) read_remainder!(copies, copies_offset, parent(from), from_ptr, n) end diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index bfc5afb8f..0b43e212d 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -181,7 +181,11 @@ function move!(dep_mod, to_space::MemorySpace, from_space::MemorySpace, to::Chun from_w = root_worker_id(from_space) # TODO: Use dep_mod to fetch with less memory usage from_raw = to_w == from_w ? unwrap(from) : fetch_copy_source(from, to) - move!(dep_mod, to_space, from_space, to_raw, from_raw) + if dep_mod === aliasing_root + move!(identity, to_space, from_space, aliasing_root(to_raw), aliasing_root(from_raw)) + else + move!(dep_mod, to_space, from_space, to_raw, from_raw) + end end return end diff --git a/test/datadeps.jl b/test/datadeps.jl index 6ef798575..2f86fce78 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1,6 +1,7 @@ import Dagger: ChunkView, Chunk, AbstractAliasing, MemorySpace, ArgumentWrapper import Dagger: aliasing, memory_space using LinearAlgebra, Graphs +using SparseArrays @testset "Hierarchical timing gates" begin # Exercise both the identity slot and the general move_rewrap path. Timing @@ -1438,3 +1439,100 @@ end end end end + +@everywhere wrapper_bump!(x, idx...) = (x[idx...] += 10; nothing) +@everywhere wrapper_snapshot(x) = (typeof(x), collect(x)) +@everywhere wrapper_sparse_update!(D::Dagger.DSparseArray) = (D.mat = 2 * D.mat; nothing) +@everywhere wrapper_sparse_update!(W) = wrapper_bump!(W, 1, 2) +@testset "Wrappers share their parent's slot" begin + # `transpose(A)` has exactly `A`'s aliasing, and a `PermutedDimsArray` or + # `ReshapedArray` is described by its parent's memory. Datadeps must give + # each such argument a slot of its own type, built around the *same* copy + # of the parent's memory as every other argument touching it, so a write + # through one is seen through the other. Each case runs a sequence of + # reads and writes, through the wrapper and its parent, and compares every + # read and the final array against running the same sequence serially. + # (On master, a remote `InOut(A)` after `In(transpose(A))` wrote `A[2,1]`.) + if nprocs() >= 2 + w = workers()[1] + P = A -> A + Vs = A -> view(A, 1:2, 1:2) + wrappers = [ + ("Transpose", A -> transpose(A), (2, 1), Float64), + ("Adjoint", A -> adjoint(A), (2, 1), Float64), + ("Adjoint (complex)", A -> adjoint(A), (2, 1), ComplexF64), + ("PermutedDimsArray", A -> PermutedDimsArray(A, (2, 1)), (2, 1), Float64), + ("ReshapedArray", A -> reshape(view(A, 1:3, 1:2), 6), (4,), Float64), + ("Transpose of a SubArray", A -> transpose(view(A, 1:3, 1:3)), (2, 1), Float64), + ("SubArray", A -> view(A, 1:2, 1:3), (1, 2), Float64), + ] + for hierarchical in (true, false) + @testset "$name (hierarchical=$hierarchical)" for (name, Wr, widx, T) in wrappers + sequences = [ + "read wrapper, write parent" => [(Wr, :R, (), w), (P, :W, (1, 2), w)], + "write parent, read wrapper" => [(P, :W, (1, 2), w), (Wr, :R, (), w)], + "write wrapper, read parent" => [(Wr, :W, widx, w), (P, :R, (), w)], + "read parent, write wrapper" => [(P, :R, (), w), (Wr, :W, widx, w)], + "write parent remotely, read wrapper locally" => [(P, :W, (1, 2), w), (Wr, :R, (), 1)], + "write part remotely, read wrapper" => [(Vs, :W, (1, 2), w), (Wr, :R, (), w)], + ] + @testset "$seq_name" for (seq_name, ops) in sequences + A = reshape(T <: Complex ? T.(1:9, 1:9) : T.(1:9), 3, 3) + B = copy(A) + expected = Any[] + for (mk, mode, idx, _) in ops + mode == :W ? wrapper_bump!(mk(B), idx...) : push!(expected, wrapper_snapshot(mk(B))) + end + reads = DTask[] + Dagger.spawn_datadeps(; hierarchical) do + for (mk, mode, idx, wid) in ops + scope = Dagger.scope(worker=wid) + if mode == :W + Dagger.@spawn scope=scope wrapper_bump!(InOut(mk(A)), idx...) + else + push!(reads, Dagger.@spawn scope=scope wrapper_snapshot(In(mk(A)))) + end + end + end + for (r, e) in zip(map(fetch, reads), expected) + @test r[1] == e[1] + @test r[2] == e[2] + end + @test A == B + end + end + end + end +end + +@testset "Wrappers share the complete sparse container" begin + if nprocs() >= 2 + write_scope = Dagger.scope(worker=first(workers())) + read_scope = Dagger.scope(worker=last(workers())) + wrappers = [("transpose", transpose), ("view", D -> view(D, 1:2, 1:2))] + @testset "$name (hierarchical=$hierarchical, write_parent=$write_parent, write_first=$write_first)" for + (name, wrap) in wrappers, hierarchical in (false, true), + write_parent in (false, true), write_first in (false, true) + D = Dagger.DSparseArray(sparse([1.0 0 2; 0 3 0; 4 0 5])) + reference = Dagger.DSparseArray(copy(D.mat)) + writer, reader = write_parent ? (D, wrap(D)) : (wrap(D), D) + ref_writer, ref_reader = write_parent ? (reference, wrap(reference)) : (wrap(reference), reference) + write_first && wrapper_sparse_update!(ref_writer) + expected = collect(ref_reader) + write_first || wrapper_sparse_update!(ref_writer) + + local result + Dagger.spawn_datadeps(; hierarchical) do + if write_first + Dagger.@spawn scope=write_scope wrapper_sparse_update!(InOut(writer)) + end + result = Dagger.@spawn scope=read_scope collect(In(reader)) + if !write_first + Dagger.@spawn scope=write_scope wrapper_sparse_update!(InOut(writer)) + end + end + @test fetch(result) == expected + @test D.mat == reference.mat + end + end +end diff --git a/test/gpu.jl b/test/gpu.jl index 8c691f096..94f81e1d8 100644 --- a/test/gpu.jl +++ b/test/gpu.jl @@ -21,6 +21,59 @@ include(joinpath(@__DIR__, "gpu_distributed.jl")) end end +@everywhere begin + wrapper_gpu_add!(x) = (x .+= 1f0; nothing) + wrapper_gpu_copy!(dst, src) = (dst .= src; nothing) +end +@testset "Datadeps wrapper and parent with a GPU task ($name)" for (name, scope) in GPU_SCOPES + # `transpose(A)` shares `A`'s aliasing. Each argument must still get a + # slot of its own type, around one shared copy of `A`'s memory per space. + # Before, a host read of `transpose(A)` followed by a device write of `A` + # handed one argument the other's slot, and the copy into the device slot + # failed with scalar indexing. + host = Dagger.scope(worker=1, thread=1) + A0 = reshape(Float32.(1:16), 4, 4) + Dagger.with_options(; scope=Dagger.UnionScope(host, scope)) do + # Host reads the transpose, then the device writes the parent + A = copy(A0) + local r + Dagger.spawn_datadeps() do + r = Dagger.@spawn scope=host collect(In(transpose(A))) + Dagger.@spawn scope=scope wrapper_gpu_add!(InOut(A)) + end + @test fetch(r) == transpose(A0) + @test A == A0 .+ 1f0 + + # Device writes the parent, then the host reads the transpose + A = copy(A0) + Dagger.spawn_datadeps() do + Dagger.@spawn scope=scope wrapper_gpu_add!(InOut(A)) + r = Dagger.@spawn scope=host collect(In(transpose(A))) + end + @test fetch(r) == transpose(A0 .+ 1f0) + @test A == A0 .+ 1f0 + + # Device writes the parent, then the device reads the transpose + A = copy(A0) + B = zeros(Float32, 4, 4) + Dagger.spawn_datadeps() do + Dagger.@spawn scope=scope wrapper_gpu_add!(InOut(A)) + Dagger.@spawn scope=scope wrapper_gpu_copy!(Out(B), In(transpose(A))) + end + @test B == transpose(A0 .+ 1f0) + @test A == A0 .+ 1f0 + + # Device writes through the transpose, then the host reads the parent + A = copy(A0) + Dagger.spawn_datadeps() do + Dagger.@spawn scope=scope wrapper_gpu_add!(InOut(transpose(A))) + r = Dagger.@spawn scope=host copy(In(A)) + end + @test fetch(r) == A0 .+ 1f0 + @test A == A0 .+ 1f0 + end +end + @testset "DArray reductions ($name)" for (name, scope) in GPU_SCOPES Dagger.with_options(; scope) do DA = rand(Blocks(4, 4), Float32, 16, 16) diff --git a/test/mpi/cpu.jl b/test/mpi/cpu.jl index 78ae0d054..ae26e63c0 100644 --- a/test/mpi/cpu.jl +++ b/test/mpi/cpu.jl @@ -476,6 +476,95 @@ end end end +# A wrapper whose memory is its parent's (`transpose(A)` has exactly `A`'s +# aliasing) must get a slot of its own type around the *one* copy of the +# parent per rank. Mirrors the Distributed "Wrappers share their parent's +# slot" testset, through the MPIWireValue `move_rewrap` path. +wrapper_bump!(x, idx...) = (x[idx...] += 10; nothing) +wrapper_snap!(dst, x) = (dst .= x; nothing) +@testset "Cross-rank wrapper dataflow" begin + r1 = min(1, nranks-1) + r2 = min(2, nranks-1) + P = A -> A + wrappers = [ + ("Transpose", A -> transpose(A), (2, 1)), + ("Adjoint", A -> adjoint(A), (2, 1)), + ("PermutedDimsArray", A -> PermutedDimsArray(A, (2, 1)), (2, 1)), + ("ReshapedArray", A -> reshape(view(A, 1:3, 1:2), 6), (4,)), + ] + @testset "$name" for (name, Wr, widx) in wrappers + sequences = [ + [(Wr, :R, (), r1), (P, :W, (1, 2), r1)], + [(P, :W, (1, 2), r1), (Wr, :R, (), r1)], + [(Wr, :W, widx, r1), (P, :R, (), r2)], + [(P, :W, (1, 2), r1), (Wr, :R, (), 0)], + ] + for ops in sequences + A = reshape(collect(1.0:9.0), 3, 3) + B = copy(A) + expected = Any[] + outs = Any[] + for (mk, mode, idx, _) in ops + if mode == :W + wrapper_bump!(mk(B), idx...) + else + push!(expected, collect(mk(B))) + push!(outs, zeros(size(mk(B)))) + end + end + Dagger.spawn_datadeps() do + i = 0 + for (mk, mode, idx, r) in ops + if mode == :W + Dagger.@spawn scope=rank_scope(r) wrapper_bump!(InOut(mk(A)), idx...) + else + i += 1 + Dagger.@spawn scope=rank_scope(r) wrapper_snap!(Out(outs[i]), In(mk(A))) + end + end + end + # Rank 0 owns the original arguments and receives the write-backs + if rank == 0 + @test A == B + @test outs == expected + end + end + end +end + +wrapper_sparse_update!(D::Dagger.DSparseArray) = (D.mat = 2 * D.mat; nothing) +wrapper_sparse_update!(W) = wrapper_bump!(W, 1, 2) +@testset "Cross-rank whole-object wrapper dataflow" begin + write_scope = rank_scope(min(1, nranks-1)) + read_scope = rank_scope(min(2, nranks-1)) + wrappers = [("transpose", transpose), ("view", D -> view(D, 1:2, 1:2))] + @testset "$name (write_parent=$write_parent, write_first=$write_first)" for + (name, wrap) in wrappers, write_parent in (false, true), write_first in (false, true) + D = Dagger.DSparseArray(sparse([1.0 0 2; 0 3 0; 4 0 5])) + reference = Dagger.DSparseArray(copy(D.mat)) + writer, reader = write_parent ? (D, wrap(D)) : (wrap(D), D) + ref_writer, ref_reader = write_parent ? (reference, wrap(reference)) : (wrap(reference), reference) + write_first && wrapper_sparse_update!(ref_writer) + expected = collect(ref_reader) + write_first || wrapper_sparse_update!(ref_writer) + + result = zeros(size(reader)) + Dagger.spawn_datadeps() do + if write_first + Dagger.@spawn scope=write_scope wrapper_sparse_update!(InOut(writer)) + end + Dagger.@spawn scope=read_scope wrapper_snap!(Out(result), In(reader)) + if !write_first + Dagger.@spawn scope=write_scope wrapper_sparse_update!(InOut(writer)) + end + end + if rank == 0 + @test result == expected + @test D.mat == reference.mat + end + end +end + @testset "ChunkView dataflow" begin # Views over a DArray block as datadeps arguments, mixed with whole-chunk # access (exercises cross-rank remainder copies through the shared backing