Skip to content
Merged
33 changes: 31 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
10 changes: 6 additions & 4 deletions ext/MPIExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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 :
Expand All @@ -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
Expand Down
76 changes: 74 additions & 2 deletions src/datadeps/aliasing.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion src/datadeps/hierarchical.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions src/datadeps/queue.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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"
Expand Down
50 changes: 25 additions & 25 deletions src/datadeps/remainders.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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}()
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion src/memory-spaces.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading