diff --git a/AGENTS.md b/AGENTS.md index ad8c5740e..3c4095758 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1071,7 +1071,7 @@ this section verbatim). Each entry is one bullet starting with `- `. reasoning about which arguments Datadeps touches, check `type_may_alias`, not `aliasing`. A single-process `spawn_datadeps` with two such values reproduces it; it is not MPI-specific. - + 100. **An argument's write history must stay sorted by write number.** `compute_remainder_for_arg!` walks `arg_history` backwards and treats each entry as newer than the ones before it. It uses each entry both to choose @@ -1217,3 +1217,110 @@ this section verbatim). Each entry is one bullet starting with `- `. 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. + + Tuple and NamedTuple aggregates need the same treatment when a child's + field storage supplies all their memory. Rebuild their headers around + shared child slots, and provide whole-copy movement of memory-bearing + children; bitstype/by-value children are already complete in the slot. + +109. **Datadeps orders nothing on `NoAliasing`, so such arguments must be + passed by value.** The dependency helpers (`_get_write_deps!` and friends) + return early for a `NoAliasing` ainfo, so no task ever waits on such a slot + through dependency tracking. Two consequences. First, the slot must be + complete when it is created: `move_rewrap` gives it `move`'s copy (never + the uninitialized-slot path), and `compute_remainder_for_arg!` schedules no + copy into or out of it. Otherwise the reader is not ordered after the copy + that fills its slot: an isbits `Vector` declared `NoAliasing`, created on + one worker and summed on another, gave a wrong sum 10 times out of 10 with + 4-thread workers -- and 0 out of 10 with 1-thread workers, where the copy + and the reader happen to run in submission order. Second, anything that + must wait for a slot's users has to track them itself: a region-end free + keyed on the slot's ainfo races the tasks still reading it (what happened + to cached `NoAliasing` copies before PR #792), which is why + `copy_users` records every reader for the matching `CopyKey` free. Test + ordering with multithreaded workers, frees with slow readers that check the + buffer is still allocated, and "nothing is copied in" with a `move!` that + raises. Beware that aliasing is per *dependency*, and "no memory" must + mean the dependency truly has none: an isbits field of a mutable `X` + (`Deps(X, InOut(:field))`) is memory inside `X`, so `field_aliasing` gives + it a `FieldAliasing` span at the field's offset. While it came out as the + isbits value's `NoAliasing`, a write to it from another memory space was + silently lost, and rejecting writes to `NoAliasing` would have broken that + documented usage outright. + +110. **A field span must not look like an indivisible container.** Bare + `ObjectAliasing` is the dispatch signal for containers whose storage must + be copied as a whole. An inline field also has an object-relative pointer, + but is only part of its parent: returning bare `ObjectAliasing` for it + makes a field/parent dependency combination hit the whole-container owner + assertion. `FieldAliasing` preserves the span while keeping it divisible. + An immutable wrapper costs no extra descriptor allocation; wrapping it in + a one-element `CombinedAliasing` vector added three allocations (80 bytes) + per field query in the isolated warmed probe. + +111. **A mutable field is writable even when its declared type is not isbits, + but its reference bytes are never a wire format.** `Any`, abstract, + `Union`, `String` and `Symbol` fields have storage inside their parent just + like `Int` fields. Describing only the value incorrectly rejects writes + when that value is `NoAliasing`. Describe the field storage and retain + referent aliasing where present. For partial copies, split bytes around + reference-valued fields and serialize scalar field values separately; + scattering raw source-process pointers into a destination object bypasses + Julia's GC and is invalid. Both Distributed and MPI need this protocol; + MPI's previous partial-field path packed bytes even for `FullCopy`. + +112. **An eager slot free must preserve storage that escapes in a task result.** + A read-only, by-value input can be returned directly, through a view, or + inside a result container. Waiting for its readers to finish is therefore + necessary but insufficient: freeing their slot before the result is + serialized produces EFAULT or a worker crash. Pass resolved reader results + to cleanup as ordinary task inputs, inspect their owner-local storage + identities, and let GC own any escaping copy. `NoAliasing` itself cannot + answer this question because it deliberately hides the buffer's memory. + +113. **Rare-copy bookkeeping should reuse existing lazy ownership tables.** + The first private-copy table allocated an empty vector in every + `AliasedObjectCacheStore`, even for entirely local regions. Making it lazy + reduced the warmed 50-region probe from 36,781 allocations /2,030,528 bytes + to 35,802 /1,955,776 bytes. Integration with `CopyKey` removes that separate + vector altogether: the existing cache tables hold copies and the lazy + `UnkeyedSlots` holds their readers. The store stays mutable to avoid + re-boxing its large immutable value on dynamically typed planning paths. + +114. **A by-value dependency keeps its contract after backend conversion.** + A host `Vector` can declare `NoAliasing` while `move` returns a device + array whose ordinary aliasing describes its device buffer. Remainder + planning must check the original dependency before comparing destination + spans: those spans can differ in both count and address space. Otherwise + a host-only NoAliasing declaration fails a host-to-device read with a span + count assertion, or schedules an unordered copy into an already complete + by-value slot. Test the host declaration alone; declaring the converted + GPU type NoAliasing as well hides this failure. + +115. **Reference-safe remainder selection must look through immutable wrappers.** + A tuple has no mutable fields of its own, but its aliasing spans can reach + a mutable child's `Any` or `String` field. Selecting raw-byte staging from + only the root's mutability then copies that child's GC pointer. Recurse + through non-array field types when selecting `FieldRemainder`, and keep + direct arrays on their ordinary staging path. Check that nested reference + slots are zero in the byte payload as well as checking their copied values. + +116. **A depth limit does not bound a shared-graph walk.** Each node of a + small DAG can reference the same child twice, making recursive inspection + revisit exponentially many paths without approaching its depth limit. + Cleanup must also cap total visits and retain storage conservatively when + proof runs out. Pass the remaining work through sibling inspections and + returned values; resetting it on each edge does not bound the total work. + Even `===` can recursively compare non-bits immutable aggregates: avoid + that comparison for matching immutable payload/result types and retain + conservatively instead. + +117. **An owning handle's fields do not reveal all the storage it retains.** + A pending `DTask` can keep an argument alive in its running work and return + it later, while its `DFuture`/`DRef` fields expose only pool identifiers. + Reflecting those fields claimed that the input did not escape, and a + Datadeps cleanup could free it while the child still used it. Treat known + work/future/pool/channel handles, foreign mutable values and nonlocal + chunks conservatively; do not block on pending work or load remote + storage merely to decide a free. Native and third-party objects can root + Julia storage through private tables without any visible field reference. diff --git a/docs/src/datadeps.md b/docs/src/datadeps.md index 2d9e27c4f..8642122e3 100644 --- a/docs/src/datadeps.md +++ b/docs/src/datadeps.md @@ -201,6 +201,23 @@ for writing memory-efficient, generic algorithms in Julia). - `Diagonal`/`Bidiagonal`/`Tridiagonal`/`SymTridiagonal` (via `Deps`, e.g. to read from the diagonal of `X`: `Dagger.@spawn sum(Deps(X, In(Diagonal)))`) - `Symbol` for field access (via `Deps`, e.g. to write to `X.value`: `Dagger.@spawn setindex!(Deps(X, InOut(:value)), :value, 42)` +A field dependency covers different memory depending on the field: + +- An isbits field of a mutable struct (an `Int`, a `Float64`, an isbits struct, + ...) is stored inside the struct, so the dependency covers exactly that field. + It may be written from any memory space: Datadeps copies just that field to + where the task runs, and back afterwards. +- A non-isbits field of a mutable struct includes the field's own storage too. + Scalar writes to fields declared as `Any`, an abstract type, a `Union`, + `String` or `Symbol` are copied back just like isbits fields. Julia values are + serialized; process-local GC pointers are never copied as bytes. +- A field referring to another memory-bearing object (an array, say) also + covers that object. Writing *into* it (e.g. `X.v .= 0`) is tracked while its + backing storage remains fixed; replacing or resizing that storage is not. +- A field of an immutable struct cannot be rebound. Writes into a memory-bearing + field value remain supported. An isbits field describes no memory, so it may + only be read (`In`). + ## In-place data movement rules Datadeps uses a specialized 5-argument function, `Dagger.move!(dep_mod, from_space::Dagger.MemorySpace, to_space::Dagger.MemorySpace, from, to)`, for managing in-place data movement. This function is an in-place variant of the more general `move` function (see [Data movement rules](@ref)) and is exclusively used within the Datadeps system. The `dep_mod` argument is usually just `identity`, but it can also be an access modifier function like `UpperTriangular`, which limits what portion of the data should be read from and written to. diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index f867b1cc5..fccbc4148 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -1736,6 +1736,17 @@ function move!(dep_mod, to_space::MPIMemorySpace, from_space::MPIMemorySpace, to move!(identity, to_space.innerSpace, from_space.innerSpace, to_val, val) end end + elseif dep_mod isa Symbol + # A field may contain a GC reference (Any, String, Union, ...). + # Serialize its value rather than packing process-local pointers. + if local_rank == from_space.rank + value = getfield(poolget(from.handle; uniform=false), dep_mod) + send_yield(value, to_space.comm, to_space.rank, tag) + elseif local_rank == to_space.rank + value = recv_yield(from_space.comm, from_space.rank, tag) + to_val = poolget(to.handle; uniform=false) + Dagger.move_field_value!(to_space.innerSpace, from_space.innerSpace, to_val, dep_mod, value) + end else # Partial copy (e.g. UpperTriangular): the destination must only # update the dep_mod-selected region. Both sides compute the @@ -1813,6 +1824,22 @@ function move!(dep_mod::Dagger.RemainderAliasing{<:MPIMemorySpace}, to_space::MP else 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 Dagger.remainder_needs_fields(chunktype(from)) + # This protocol choice depends only on the rank-uniform chunktype. + # Field values travel through Julia serialization; dense/device + # arrays retain the staging-buffer protocol below. + if local_rank == from_space.rank + from_raw = poolget(from.handle; uniform=false) + copies = Dagger.gather_field_remainder(from_raw, Iterators.map(first, dep_mod.spans)) + send_yield(copies, to_space.comm, to_space.rank, tag) + elseif local_rank == to_space.rank + copies = recv_yield(from_space.comm, from_space.rank, tag) + to_raw = poolget(to.handle; uniform=false) + Dagger.scatter_field_remainder!(to_raw, copies, Iterators.map(last, dep_mod.spans)) + Base.Threads.atomic_fence() + end + return + end if local_rank == from_space.rank # Gather the source spans into a host buffer (device arrays pack # via multi_span_gather! / one KA launch, then a single DtoH) @@ -1939,6 +1966,8 @@ mpi_remap_ainfo(a::Dagger.ContiguousAliasing, owner::Int) = Dagger.ContiguousAliasing(mpi_remap_span(a.span, owner)) mpi_remap_ainfo(a::Dagger.ObjectAliasing, owner::Int) = Dagger.ObjectAliasing(mpi_remap_ptr(a.ptr, owner), a.sz) +mpi_remap_ainfo(a::Dagger.FieldAliasing, owner::Int) = + Dagger.FieldAliasing(mpi_remap_ainfo(a.storage, owner)) function mpi_remap_ainfo(a::Dagger.StridedAliasing{T,N,S}, owner::Int) where {T,N,S} base_ptr = mpi_remap_ptr(a.base_ptr, owner) return Dagger.StridedAliasing{T,N,typeof(base_ptr.space)}(base_ptr, @@ -2173,15 +2202,21 @@ function move_rewrap(accel::MPIAcceleration, cache::AliasedObjectCache, from_pro # N.B. The predicate depends only on the two spaces and the destination # type, all rank-uniform, so every rank takes the same branch and the # collectives below stay matched. + # + # An argument whose aliasing describes no memory is passed by value: its + # slot must be the transferred copy, never an uninitialized buffer (see + # the generic `move_rewrap`). The aliasing is the same (collective) query + # `aliased_object!` would make, just made first. + ainfo = aliasing(cache.accel, w, identity) T_dest = move_type(mpi_inner_proc(as_mpi_proc(from_proc, from_space)), mpi_inner_proc(as_mpi_proc(to_proc, to_space)), T) - if Dagger.slot_may_be_uninit(from_space, to_space, T_dest) - return aliased_object!(cache, w) do w + if Dagger.slot_may_be_uninit(from_space, to_space, T_dest) && Dagger.describes_memory(ainfo)::Bool + return aliased_object!(cache, w; ainfo) do w return mpi_endpoint_alloc(accel, to_proc, to_space, T_dest, w) end end - # The transfer makes its payload freeable on the destination rank - return aliased_object!(cache, w) do w + # The transfer makes its payload freeable on the destination rank. + return aliased_object!(cache, w; ainfo) do w return mpi_endpoint_transfer(accel, from_proc, to_proc, from_space, to_space, w) end end diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index 40d5edee5..f8eab85a8 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -417,7 +417,7 @@ struct HistoryEntry task::WriterProducer end -struct AliasedObjectCacheStore +mutable struct AliasedObjectCacheStore accel::Acceleration keys::Vector{AbstractAliasing} derived::Dict{AbstractAliasing,AbstractAliasing} @@ -698,7 +698,7 @@ function aliased_object!(f, cache::AliasedObjectCache, x; ainfo=aliasing(cache.a # the second distinct argument would be handed the first one's slot. There is # no aliasing to preserve, so each value gets its own copy, which is recorded # under a fresh key so that region teardown still frees it. - aliasing_has_identity(ainfo) || return aliased_object_unkeyed!(f, cache, x) + (describes_memory(ainfo)::Bool && aliasing_has_identity(ainfo)) || return aliased_object_unkeyed!(f, cache, x) x_space = memory_space(x) if !is_key_present(cache, x_space, ainfo) # Preserve the object's memory-space/processor pairing when inserting @@ -762,6 +762,7 @@ end function aliased_object_unkeyed!(f, cache::AliasedObjectCache, x) x_space = memory_space(x) + x_space == cache.space && x isa Chunk && return x y = f(x) @assert y isa Chunk "Didn't get a Chunk from functor" # Only a copy made for another space is ours to free. `y === x` is the @@ -1143,7 +1144,10 @@ function _populate_arg_deps!(state::DataDepsState, infos::Vector{TaskArgInfo}, # Anything per-use added there would be skipped from the second use on. if dep_full === nothing dep_full = DataDepsTaskDependency(arg_chunk, dep) - populate_argument_info!(state, dep_full.arg_w, memory_space(arg_chunk)) + ainfo = populate_argument_info!(state, dep_full.arg_w, memory_space(arg_chunk)) + if dep_full.writedep && !(describes_memory(ainfo)::Bool) + throw_unwritable(arg_chunk, dep_full.arg_w.dep_mod) + end if !checking_uniformity if memo === nothing memo = state.dep_memo[arg_chunk] = dep_full @@ -1159,6 +1163,21 @@ function _populate_arg_deps!(state::DataDepsState, infos::Vector{TaskArgInfo}, push!(infos, TaskArgInfo(arg_chunk, pos, may_alias, inplace_move, dep_start, length(deps_vec))) return end +# An argument whose aliasing describes no memory is read-only and passed by +# value (see `move_rewrap` and `compute_remainder_for_arg!`): Datadeps never +# copies a write to it anywhere, so a write would be silently lost. The aliasing +# is rank-uniform under MPI, so every rank throws together. +@noinline function throw_unwritable(arg, dep_mod) + T = arg isa Chunk ? chunktype(arg) : typeof(arg) + target = dep_mod === identity ? "a `$T` argument" : "a `$T` argument (through `$dep_mod`)" + throw(ArgumentError(""" + Datadeps cannot take write access (`Out`/`InOut`) to $target whose aliasing describes no memory. + + Such an argument (e.g. one whose `aliasing` returns `NoAliasing()`) is read-only + and passed by value: tasks in other memory spaces get a copy, and nothing is + ever copied back, so a write would be lost. Pass it as `In`, or give its type an + `aliasing` method that describes the memory it holds.""")) +end function populate_argument_info!(state::DataDepsState, arg_w::ArgumentWrapper, origin_space::MemorySpace) # Initialize ownership and history if !haskey(state.arg_owner, arg_w) @@ -1608,24 +1627,120 @@ function add_unkeyed_user!(unkeyed::UnkeyedSlots, state::DataDepsState, arg_w::A end """ - push_copy_users_syncdeps!(state, key::CopyKey, syncdeps) + copy_users(state, key::CopyKey) -Add to `syncdeps` every task that used the slot holding the `CopyKey` copy -`key`, so that the copy's region-end free waits for them (see `UnkeyedSlots`). +Return every task that used the slot holding `key`, so its region-end free +can wait for them and inspect their results (see `UnkeyedSlots`). """ -function push_copy_users_syncdeps!(state::DataDepsState, key::CopyKey, syncdeps) +function copy_users(state::DataDepsState, key::CopyKey) unkeyed = state.unkeyed_slots idx = unkeyed === nothing ? 0 : get(unkeyed.copy_slot, key.id, 0) # Every `CopyKey` copy is made inside `generate_slot!`, which attributes it # to its slot. Carrying on without one would free the copy with nothing to # wait for -- the use-after-free this exists to prevent. idx == 0 && error("No slot recorded for Datadeps copy $key; cannot determine free syncdeps") - for user in unkeyed.users[idx] + return unkeyed.users[idx] +end +function push_copy_users_syncdeps!(state::DataDepsState, key::CopyKey, syncdeps) + for user in copy_users(state, key) push!(syncdeps, ThunkSyncdep(user)) end return end +const UNKEYED_RETENTION_BUDGET = 256 + +# These handles can own values or pending work through storage that field +# reflection cannot follow. Inspecting or waiting for them is not cleanup work. +opaque_retention_owner(x) = + x isa Union{DTask,Thunk,ThunkFuture,DFuture,DRef,FileRef,Future,RemoteChannel,Task,Channel} +@static if isdefined(MemPool, :DEvent) + opaque_retention_owner(::MemPool.DEvent) = true +end + +function free_unkeyed_copy!(copy::Chunk, results...) + payload = unwrap(copy) + budget = UNKEYED_RETENTION_BUDGET + for result in results + budget = unkeyed_retention_budget(result, payload, 0, budget) + budget < 0 && return + end + unsafe_free!(payload) + return +end + +# `NoAliasing` deliberately hides the copy's memory from dependency tracking, +# so use object identity / Base's storage identities to inspect returned values. +# Bound both depth and total visits: a shared DAG can expand exponentially even +# at a shallow depth. Exhaustion conservatively leaves storage to its GC owner. +retains_unkeyed_storage(result, payload, depth::Int=0) = + unkeyed_retention_budget(result, payload, depth, UNKEYED_RETENTION_BUDGET) < 0 + +# Negative means retain; otherwise return the budget left for the next child. +# Passing one integer through the walk avoids a visited set or mutable counter. +function unkeyed_retention_budget(result, payload, depth::Int, budget::Int)::Int + if typeof(result) === typeof(payload) + # Equality of non-bits immutable aggregates can recursively revisit a + # shared DAG before the walk even starts. A matching immutable type is + # sufficient uncertainty to retain; mutable values use pointer identity. + T = typeof(payload) + (!ismutabletype(T) && !isbitstype(T)) && return -1 + result === payload && return -1 + end + (budget <= 0 || depth >= 128) && return -1 + budget -= 1 + opaque_retention_owner(result) && return -1 + if result isa Chunk + is_local(current_acceleration(), processor(result)) || return -1 + return unkeyed_retention_budget(unwrap(result), payload, depth + 1, budget) + elseif result isa AbstractArray + if payload isa AbstractArray && Base.mightalias(result, payload) + return -1 + end + p = parent(result) + if p !== result + budget = unkeyed_retention_budget(p, payload, depth + 1, budget) + budget < 0 && return budget + end + isbitstype(eltype(result)) && return budget + if result isa Array + for i in eachindex(result) + child = isassigned(result, i) ? result[i] : nothing + budget = unkeyed_retention_budget(child, payload, depth + 1, budget) + budget < 0 && return budget + end + elseif p === result + # An arbitrary non-bits array may prohibit scalar indexing. + return -1 + end + elseif !(isbits(result) || result isa Union{String,Symbol,Type,Module}) + T = typeof(result) + if ismutabletype(T) + mod = parentmodule(T) + # A foreign mutable value can own Julia storage through native or + # pool tables even when its visible fields contain only IDs. + (mod === Core || mod === Base) || return -1 + end + isstructtype(T) || return budget + for i in 1:fieldcount(T) + child = isdefined(result, i) ? getfield(result, i) : nothing + budget = unkeyed_retention_budget(child, payload, depth + 1, budget) + budget < 0 && return budget + end + end + return budget +end + +function enqueue_cached_free!(state::DataDepsState, key::CopyKey, copy::Chunk, scope, syncdeps) + users = copy_users(state, key) + Dagger.@spawn scope=scope syncdeps=syncdeps meta=true tag=datadeps_task_tag() free_unkeyed_copy!(copy, users...) + return +end +function enqueue_cached_free!(state::DataDepsState, key::AbstractAliasing, copy::Chunk, scope, syncdeps) + Dagger.@spawn scope=scope syncdeps=syncdeps tag=datadeps_task_tag() Dagger.unsafe_free!(copy) + return +end + # Make a copy of each piece of data on each worker # memory_space => {arg => copy_of_arg} isremotehandle(x) = false @@ -1835,6 +1950,19 @@ move_rewrap_parts(x) = nothing move_rewrap_child_types(::Type) = nothing move_rewrap_header_mode(::Type) = :none +# Tuple aggregates share their children's storage without becoming a child's +# cached leaf slot when both describe exactly the same memory. +move_rewrap_parts(x::Tuple) = (x, nothing) +move_rewrap_build(::Type{<:Tuple}, children, ::Nothing) = children +move_rewrap_child_types(::Type{T}) where {T<:Tuple} = fieldtypes(T) +move_rewrap_result_type(::Type{<:Tuple}, child_types, ::Nothing) = Tuple{child_types...} +move_rewrap_parts(x::NamedTuple) = (values(x), nothing) +move_rewrap_build(::Type{<:NamedTuple{names}}, children, ::Nothing) where names = + NamedTuple{names}(children) +move_rewrap_child_types(::Type{T}) where {T<:NamedTuple} = fieldtypes(T) +move_rewrap_result_type(::Type{<:NamedTuple{names}}, child_types, ::Nothing) where names = + NamedTuple{names,Tuple{child_types...}} + # SubArray: parent payload + indices header move_rewrap_parts(x::SubArray) = ((parent(x),), parentindices(x)) move_rewrap_build(::Type{<:SubArray}, (p,), inds) = view(p, inds...) @@ -1908,13 +2036,14 @@ function move_rewrap(accel, cache::AliasedObjectCache, from_proc::Processor, to_ # establishes the contents, and for a wrapper (a view, say) it copies # only the wrapper's own spans rather than the whole backing array. # See `slot_may_be_uninit` for why this is safe. + ainfo = aliasing(cache.accel, data, identity) T_dest = move_type(from_proc, to_proc, typeof(data)) - if slot_may_be_uninit(from_space, to_space, T_dest) - return aliased_object!(cache, data) do data + if slot_may_be_uninit(from_space, to_space, T_dest) && describes_memory(ainfo)::Bool + return aliased_object!(cache, data; ainfo) do data return remotecall_endpoint_alloc(accel, to_proc, to_space, T_dest, alloc_header(data)) end end - return aliased_object!(cache, data) do data + return aliased_object!(cache, data; ainfo) do data return remotecall_endpoint_transfer(accel, from_proc, to_proc, from_space, to_space, data) do accel, from_proc, to_proc, from_space, to_space, data return tochunk(libc_backed(move(from_proc, to_proc, data)), to_proc, to_space) end diff --git a/src/datadeps/hierarchical.jl b/src/datadeps/hierarchical.jl index d7b41b6ec..41a7bea40 100644 --- a/src/datadeps/hierarchical.jl +++ b/src/datadeps/hierarchical.jl @@ -2008,7 +2008,7 @@ function _hierarchical_copy_from_and_free!(partition_states::Vector{DataDepsStat end end end - Dagger.@spawn scope=free_scope syncdeps=free_syncdeps tag=datadeps_task_tag() Dagger.unsafe_free!(remote_arg) + enqueue_cached_free!(state, ainfo, remote_arg, free_scope, free_syncdeps) end end end diff --git a/src/datadeps/queue.jl b/src/datadeps/queue.jl index 281706d66..15165fd35 100644 --- a/src/datadeps/queue.jl +++ b/src/datadeps/queue.jl @@ -242,7 +242,7 @@ function distribute_tasks!(queue::DataDepsTaskQueue) # wait for every task that used its slot instead. ainfo isa CopyKey && push_copy_users_syncdeps!(state, ainfo, free_syncdeps) # `tag` keeps the free task rank-uniform under MPI/uniform execution. - Dagger.@spawn scope=free_scope syncdeps=free_syncdeps tag=datadeps_task_tag() Dagger.unsafe_free!(remote_arg) + enqueue_cached_free!(state, ainfo, remote_arg, free_scope, free_syncdeps) end end end diff --git a/src/datadeps/remainders.jl b/src/datadeps/remainders.jl index 8fe467b57..edd3fec0e 100644 --- a/src/datadeps/remainders.jl +++ b/src/datadeps/remainders.jl @@ -121,6 +121,23 @@ function compute_remainder_for_arg!(state::DataDepsState, all_local && return NoAliasing(), 0 end + # A move may change the concrete value type (e.g. Array -> device array), + # and its physical aliasing can then differ. The original dependency's + # by-value contract still applies to every converted slot. + origin_ainfo = get(state.ainfo_cache, arg_w, nothing) + if origin_ainfo === nothing + # A wrapper containing handles can be rebuilt even in its own space. + origin_ainfo = aliasing!(state, state.arg_origin[arg_w.arg], arg_w) + end + describes_memory(origin_ainfo)::Bool || return NoAliasing(), 0 + + target_ainfo = aliasing!(state, target_space, arg_w) + + # An argument whose aliasing describes no memory is read-only and passed by + # value: its slot in `target_space` is already `move`'s copy of it (see + # `move_rewrap`), so nothing is ever copied into it -- nor back to its origin. + describes_memory(target_ainfo)::Bool || return NoAliasing(), 0 + # Whole-object containers (e.g. `DSparseArray`) reallocate their entire # storage on every write, so they can never be *partially* current in a # memory space -- the whole object is current in exactly one space: the most @@ -129,7 +146,7 @@ function compute_remainder_for_arg!(state::DataDepsState, # `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)) + if aliases_as_whole(target_ainfo) history = state.arg_history[arg_w] source_space = isempty(history) ? owner_space : history[end].space return source_space == target_space ? (NoAliasing(), 0) : (FullCopy(source_space), 0) @@ -582,10 +599,13 @@ function move!(dep_mod::RemainderAliasing{S}, to_space::MemorySpace, from_space: # Gather source spans into a host buffer (device arrays pack via KA first). # Pin when the source is device memory so DtoH hits page-locked host RAM. copies = remotecall_fetch(root_worker_id(from_space), from_space, dep_mod, from) do from_space, dep_mod, from + from_raw = unwrap(from) + if remainder_needs_fields(typeof(from_raw)) + return gather_field_remainder(from_raw, Iterators.map(first, dep_mod.spans)) + end len = sum(span_tuple->span_len(span_tuple[1]), dep_mod.spans) copies = Vector{UInt8}(undef, len) pin_buffer!(gpu_memory_kind(from_space), copies) - from_raw = unwrap(from) with_context!(from_space) # `from_raw` is preserved alongside `copies`. For device-backed arrays # (`CuArray`, `ROCArray`, `CLArray`, …) the underlying device memory is @@ -605,6 +625,11 @@ function move!(dep_mod::RemainderAliasing{S}, to_space::MemorySpace, from_space: # Scatter into the destination spans (pin again after remotecall deserialize) to_raw = unwrap(to) with_context!(to_space) + if copies isa FieldRemainder + scatter_field_remainder!(to_raw, copies, Iterators.map(last, dep_mod.spans)) + Base.Threads.atomic_fence() + return + end pin_buffer!(gpu_memory_kind(to_space), copies) # See the gather above -- the same finalizer lifetime hazard applies to # `to_raw` on the scatter side. @@ -644,7 +669,135 @@ function read_remainder!(copies::Vector{UInt8}, copies_offset::UInt64, from::Den copies_typed = unsafe_wrap(Vector{eltype(from)}, Ptr{eltype(from)}(pointer(copies, copies_offset)), n) copyto!(copies_typed, 1, from_vec, Int(from_offset_n), Int(n)) end +# Whether `[ptr, ptr+n)` lies in the inline storage of the mutable object `x`, +# as an isbits field of it does (see `field_aliasing`). +function span_is_inline(x, ptr::UInt64, n::UInt64) + ismutable(x) || return false + base = UInt64(pointer_from_objref(x)) + return base <= ptr && ptr + n <= base + UInt64(sizeof(typeof(x))) +end +# A mutable object's reference fields contain process-local GC pointers. Keep +# those out of the byte payload and serialize scalar field values separately. +struct FieldRemainder + bytes::Vector{UInt8} + values::Vector{Pair{UInt64,Any}} +end + +function remainder_needs_fields(::Type{T}) where T + T <: AbstractArray && return false + isbitstype(T) && return false + isconcretetype(T) || return true + fields = fieldtypes(T) + ismutabletype(T) && any(FT -> !isbitstype(FT), fields) && return true + # Immutable wrappers have no writable storage of their own, but their + # spans can reach a mutable child's reference-valued fields. + return any(remainder_needs_fields, fields) +end + +function gather_field_remainder(from, spans) + len = sum(span_len, spans; init=UInt64(0)) + # Omitted reference slots stay zero, never uninitialized or pointer bytes. + copies = FieldRemainder(zeros(UInt8, len), Pair{UInt64,Any}[]) + offset = UInt64(1) + for span in spans + read_field_remainder!(copies, offset, from, UInt64(span_start(span)), UInt64(span_len(span))) + offset += span_len(span) + end + return copies +end +function scatter_field_remainder!(to, copies::FieldRemainder, spans) + offset = UInt64(1) + for span in spans + write_field_remainder!(copies, offset, to, UInt64(span_start(span)), UInt64(span_len(span))) + offset += span_len(span) + end + return +end +function read_field_remainder!(copies::FieldRemainder, offset::UInt64, from::AbstractArray, ptr::UInt64, n::UInt64) + read_remainder!(copies.bytes, offset, from, ptr, n) +end +function read_field_remainder!(copies::FieldRemainder, offset::UInt64, from::T, ptr::UInt64, n::UInt64) where T + if !span_is_inline(from, ptr, n) + holder = find_object_holding_ptr(from, ptr) + return read_field_remainder!(copies, offset, holder, ptr, n) + end + base = UInt64(pointer_from_objref(from)) + cursor = ptr + stop = ptr + n + GC.@preserve from copies begin + for i in 1:fieldcount(T) + isbitstype(fieldtype(T, i)) && continue + field_start = base + UInt64(fieldoffset(T, i)) + field_stop = field_start + UInt64(field_storage_size(T, i)) + (field_start >= stop || field_stop <= ptr) && continue + @assert ptr <= field_start && field_stop <= stop "Remainder splits a reference-valued field" + unsafe_copyto!(pointer(copies.bytes, offset + cursor - ptr), Ptr{UInt8}(cursor), field_start - cursor) + value = getfield(from, i) + # Memory-bearing fields retain the destination binding; their + # referent spans carry the contents separately, as for array fields. + if !(describes_memory(aliasing(value))::Bool) + push!(copies.values, (offset + field_start - ptr) => value) + end + cursor = field_stop + end + unsafe_copyto!(pointer(copies.bytes, offset + cursor - ptr), Ptr{UInt8}(cursor), stop - cursor) + end + return +end +function write_field_remainder!(copies::FieldRemainder, offset::UInt64, to::AbstractArray, ptr::UInt64, n::UInt64) + write_remainder!(copies.bytes, offset, to, ptr, n) +end +function write_field_remainder!(copies::FieldRemainder, offset::UInt64, to::T, ptr::UInt64, n::UInt64) where T + if !span_is_inline(to, ptr, n) + holder = find_object_holding_ptr(to, ptr) + return write_field_remainder!(copies, offset, holder, ptr, n) + end + base = UInt64(pointer_from_objref(to)) + cursor = ptr + stop = ptr + n + GC.@preserve to copies begin + for i in 1:fieldcount(T) + isbitstype(fieldtype(T, i)) && continue + field_start = base + UInt64(fieldoffset(T, i)) + field_stop = field_start + UInt64(field_storage_size(T, i)) + (field_start >= stop || field_stop <= ptr) && continue + @assert ptr <= field_start && field_stop <= stop "Remainder splits a reference-valued field" + unsafe_copyto!(Ptr{UInt8}(cursor), pointer(copies.bytes, offset + cursor - ptr), field_start - cursor) + key = offset + field_start - ptr + for value in copies.values + if first(value) == key + setfield!(to, i, last(value)) + break + end + end + cursor = field_stop + end + unsafe_copyto!(Ptr{UInt8}(cursor), pointer(copies.bytes, offset + cursor - ptr), stop - cursor) + end + return +end + +# An ordinary mutable struct's aliasing includes memory reachable through its +# fields. Resolve those spans without requiring a pointer hook per struct type. +function find_object_holding_ptr(x::T, ptr::UInt64) where T + for i in 1:fieldcount(T) + isdefined(x, i) || continue + value = getfield(x, i) + isbits(value) && continue + for span in memory_spans(aliasing(value)) + if UInt64(span_start(span)) <= ptr <= UInt64(span_end(span)) + return value + end + end + end + throw(ArgumentError("No field of $T holds remainder pointer $ptr")) +end + function read_remainder!(copies::Vector{UInt8}, copies_offset::UInt64, from, from_ptr::UInt64, n::UInt64) + if span_is_inline(from, from_ptr, n) + GC.@preserve from unsafe_copyto!(pointer(copies, copies_offset), Ptr{UInt8}(from_ptr), n) + return + end real_from = find_object_holding_ptr(from, from_ptr) return read_remainder!(copies, copies_offset, real_from, from_ptr, n) end @@ -670,6 +823,10 @@ function write_remainder!(copies::Vector{UInt8}, copies_offset::UInt64, to::Dens copyto!(to_vec, Int(to_offset_n), copies_typed, 1, Int(n)) end function write_remainder!(copies::Vector{UInt8}, copies_offset::UInt64, to, to_ptr::UInt64, n::UInt64) + if span_is_inline(to, to_ptr, n) + GC.@preserve to unsafe_copyto!(Ptr{UInt8}(to_ptr), pointer(copies, copies_offset), n) + return + end real_to = find_object_holding_ptr(to, to_ptr) return write_remainder!(copies, copies_offset, real_to, to_ptr, n) end diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index 0b43e212d..04d8e4721 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -172,8 +172,33 @@ function unwrap(handle::DRef) @assert root_worker_id(handle) == myid() "DRef $handle is not owned by this process: $(root_worker_id(handle)) != $(myid())" return MemPool.poolget(handle) end -move!(dep_mod, to_space::MemorySpace, from_space::MemorySpace, to::T, from::F) where {T,F} = +function move!(dep_mod, to_space::MemorySpace, from_space::MemorySpace, to::T, from::F) where {T,F} + # A field dependency (`Deps(x, InOut(:field))`) of any struct. Handled here + # rather than by a `dep_mod::Symbol` method, which would be ambiguous with + # every `move!` that specializes the values instead (`Chunk`s, arrays, ...). + if dep_mod isa Symbol && T === F + return move_field!(to_space, from_space, to, from, dep_mod) + end throw(ArgumentError("No `move!` implementation defined for $F -> $T")) +end +# Aggregates cannot rebind their fields, but their memory-bearing children can +# be updated in place. No-memory children already arrived by value with the slot. +function move!(::typeof(identity), to_space::MemorySpace, from_space::MemorySpace, + to::Tuple, from::Tuple) + length(to) == length(from) || throw(DimensionMismatch("Tuple copy lengths differ")) + for i in eachindex(to) + from_child = from[i] + describes_memory(aliasing(from_child))::Bool || continue + move!(identity, to_space, from_space, to[i], from_child) + end + return +end +function move!(::typeof(identity), to_space::MemorySpace, from_space::MemorySpace, + to::NamedTuple, from::NamedTuple) + keys(to) == keys(from) || throw(ArgumentError("NamedTuple copy keys differ")) + return move!(identity, to_space, from_space, values(to), values(from)) +end + function move!(dep_mod, to_space::MemorySpace, from_space::MemorySpace, to::Chunk, from::Chunk) to_w = root_worker_id(to_space) remotecall_wait(to_w, dep_mod, to_space, from_space, to, from) do dep_mod, to_space, from_space, to, from @@ -204,16 +229,29 @@ function move!(dep_mod, to_space::MemorySpace, from_space::MemorySpace, to::Base to[] = from[] return end -function move!(dep_mod::Symbol, to_space::MemorySpace, from_space::MemorySpace, to::Base.RefValue{T}, from::Base.RefValue{T}) where {T} - to_f = getfield(to, dep_mod) - from_f = getfield(from, dep_mod) +move!(dep_mod::Symbol, to_space::MemorySpace, from_space::MemorySpace, to::Base.RefValue{T}, from::Base.RefValue{T}) where {T} = + move_field!(to_space, from_space, to, from, dep_mod) + +""" + move_field!(to_space, from_space, to, from, field::Symbol) + +Copy one field of `from` into `to`, for a field dependency (see +`field_aliasing`). +""" +function move_field!(to_space::MemorySpace, from_space::MemorySpace, to::T, from::T, field::Symbol) where T + return move_field_value!(to_space, from_space, to, field, getfield(from, field)) +end +function move_field_value!(to_space::MemorySpace, from_space::MemorySpace, to::T, field::Symbol, from_f) where T + to_f = getfield(to, field) if to_f isa AbstractArray && from_f isa AbstractArray && axes(to_f) == axes(from_f) # Update the field's storage in place: aliasing spans computed when the # destination slot was created point into that storage, and rebinding # the field would silently disconnect them move!(to_space, from_space, to_f, from_f) + elseif ismutabletype(T) + setfield!(to, field, from_f) else - setfield!(to, dep_mod, from_f) + throw(ArgumentError("Cannot copy field `$field` of an immutable `$T`")) end return end @@ -545,6 +583,41 @@ Base.:(==)(ca1::CombinedAliasing, ca2::CombinedAliasing) = Base.hash(ca1::CombinedAliasing, h::UInt) = hash(ca1.sub_ainfos, hash(CombinedAliasing, h)) +""" + describes_memory(ainfo::AbstractAliasing) -> Bool + +Whether `ainfo` refers to any memory at all. `false` means a value with this +aliasing shares no memory with any other value: `NoAliasing`, and a +`CombinedAliasing` made only of such parts -- including an empty one, which is +what a struct whose fields all report `NoAliasing` gets. + +Datadeps shares one slot per memory space between arguments whose aliasing +compares equal (see `aliased_object!`). Aliasing that describes no memory cannot +be used that way: it carries no identity (every `NoAliasing()` compares equal), +so sharing would hand one argument another argument's value, and there is no +shared memory to preserve. Such arguments get a slot of their own instead. A +custom `AbstractAliasing` that likewise describes no memory should add a method +returning `false`. + +`UnknownAliasing` returns `true`: it means "may alias any memory", not "aliases +none". Two arguments with unknown aliasing may be one object reached through +different wrappers, which separate copies would silently split. (Dagger's own +`aliasing` methods throw rather than return it.) + +Datadeps treats such arguments as read-only, by-value inputs: `Out` and `InOut` +are rejected, a slot in another memory space is a complete `move` copy rather +than an uninitialized buffer, and no later copy-to or copy-back is scheduled. +Private copies are released after their readers finish, except when retained +by a task result, which then owns their lifetime through GC. + +Dependency tracking skips bare `NoAliasing` alone. Empty `CombinedAliasing` +values retain their existing per-argument dependency tracking. +""" +describes_memory(::AbstractAliasing) = true +describes_memory(::NoAliasing) = false +describes_memory(ca::CombinedAliasing) = any(describes_memory, ca.sub_ainfos) +describes_memory(x::AliasingWrapper) = describes_memory(x.inner) + struct ObjectAliasing{S<:MemorySpace} <: AbstractAliasing ptr::RemotePtr{Cvoid,S} sz::UInt @@ -562,6 +635,14 @@ function memory_spans(oa::ObjectAliasing{S}) where S return [span] end +"A field's storage: divisible alongside its parent, unlike a whole-object container." +struct FieldAliasing{A<:AbstractAliasing} <: AbstractAliasing + storage::A +end +memory_spans(fa::FieldAliasing) = memory_spans(fa.storage) +Base.:(==)(a::FieldAliasing, b::FieldAliasing) = a.storage == b.storage +Base.hash(a::FieldAliasing, h::UInt) = hash(a.storage, hash(FieldAliasing, h)) + # Acceleration entry point used by Datadeps. Unwrap whole-object containers # (e.g. views of `DSparseArray`) before computing aliasing. SPMD backends # (MPI) overload this for `Chunk`/`ChunkView` to broadcast owner-computed @@ -569,10 +650,41 @@ end aliasing(accel::Acceleration, x, T) = aliasing_unwrapped(x, T) function aliasing(x, dep_mod) if dep_mod isa Symbol - return aliasing(getfield(x, dep_mod)) + return field_aliasing(x, dep_mod) end return aliasing(dep_mod(x)) end + +field_storage_size(::Type{T}, i::Int) where T = + (i < fieldcount(T) ? fieldoffset(T, i + 1) : sizeof(T)) - fieldoffset(T, i) + +""" + field_aliasing(x, field::Symbol) -> AbstractAliasing + +The aliasing of a `Deps(x, In(:field))`-style dependency on one field of `x`. + +- Every field of a mutable struct includes its own storage inside `x`, so + rebinding scalar, `Any`, `Union`, string and symbol fields is tracked and + copied back. Memory reachable through a reference field is included too. +- A field of an immutable struct aliases its value. An isbits value then + describes no writable memory; an array value still supports writes through + the field. +""" +function field_aliasing(x::T, field::Symbol) where T + idx = Base.fieldindex(T, field) + FT = fieldtype(T, idx) + if ismutabletype(T) + addr = UInt(pointer_from_objref(x)) + UInt(fieldoffset(T, idx)) + # A field is a splittable part of its parent object, unlike a bare + # ObjectAliasing (the contract for indivisible containers). + own = ObjectAliasing(RemotePtr{Cvoid}(addr, CPURAMMemorySpace(myid())), field_storage_size(T, idx)) + isbitstype(FT) && return FieldAliasing(own) + referent = aliasing(getfield(x, field)) + describes_memory(referent)::Bool || return FieldAliasing(own) + return FieldAliasing(CombinedAliasing(AbstractAliasing[own, referent])) + end + return aliasing(getfield(x, field)) +end function aliasing(x::T) where T if isbits(x) return NoAliasing() diff --git a/test/datadeps.jl b/test/datadeps.jl index a97720a5e..3e75a7960 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1054,10 +1054,12 @@ function test_datadeps(;args_chunks::Bool, for proc in exec_procs @test proc in scope_procs end - for proc in scope_procs - proc == Dagger.ThreadProc(1, 1) && continue - @test proc in exec_procs - end + # The unpinned tasks may all finish on one eligible processor. Exercise + # each processor in the outer scope with an explicitly placed task. + scoped_procs = fetch.(Dagger.spawn_datadeps() do + [Dagger.@spawn scope=ExactScope(proc) Dagger.task_processor() for proc in scope_procs] + end) + @test scoped_procs == scope_procs # Inner Scope @test_throws Dagger.Sch.SchedulingException Dagger.spawn_datadeps() do @@ -1234,6 +1236,109 @@ include(joinpath(@__DIR__, "array", "sparse_defs.jl")) end end +include("field_deps_defs.jl") +@testset "Nested field remainder payload" test_nested_field_remainders() + +# The same body runs under MPI from test/mpi/cpu.jl. +@testset "Isbits Field Dependencies" begin + on(w) = Dagger.scope(worker=w) + @testset "hierarchical=$hierarchical" for hierarchical in (false, true) + @testset "in place" test_isbits_field_writes(; hierarchical, scope=on(1)) + @testset "reference fields in place" test_reference_field_writes(; hierarchical, scope=on(1)) + @testset "nested fields in place" test_nested_field_writes(; hierarchical, scope=on(1)) + if nprocs() >= 3 + w1, w2 = workers()[1], workers()[2] + @testset "on another worker" test_isbits_field_writes(; hierarchical, scope=on(w1)) + @testset "read on a third worker" test_isbits_field_writes(; hierarchical, scope=on(w1), reader_scope=on(w2)) + @testset "reference fields across workers" test_reference_field_writes(; hierarchical, scope=on(w1), reader_scope=on(w2)) + @testset "nested fields across workers" test_nested_field_writes(; hierarchical, scope=on(w1), reader_scope=on(w2)) + end + end +end + +include("noaliasing_defs.jl") +@testset "Bounded escaped-storage inspection" test_noaliasing_retention_budget() +@testset "Pending handles retain escaped storage" test_noaliasing_pending_handles() + +# The same bodies run under MPI from test/mpi/noaliasing_args.jl. +@testset "NoAliasing Arguments" begin + on(w) = Dagger.scope(worker=w) + @testset "$(nameof(mk)), hierarchical=$hierarchical" for mk in (noalias_val, noalias_wrap), hierarchical in (false, true) + @testset "write access is rejected" begin + test_noaliasing_write_rejected(; mk, hierarchical, scope=on(1)) + end + mk === noalias_val && @testset "write access to an immutable isbits field is rejected" begin + test_immutable_field_write_rejected(; hierarchical, scope=on(1)) + end + @testset "in place" begin + test_noaliasing_args(; mk, hierarchical, src_scope=_->on(1), dst_scope=_->on(1)) + end + if nprocs() >= 3 + w1, w2 = workers()[1], workers()[2] + @testset "in place, on a worker" begin + test_noaliasing_args(; mk, hierarchical, src_scope=_->on(w1), dst_scope=_->on(w1)) + end + # Every value lands in the same destination space, each needing a + # slot of its own there. + @testset "across memory spaces" begin + test_noaliasing_args(; mk, hierarchical, src_scope=_->on(w1), dst_scope=_->on(w2)) + end + @testset "across memory spaces, mixed" begin + test_noaliasing_args(; mk, hierarchical, nvals=6, + src_scope=i->on(isodd(i) ? 1 : w1), + dst_scope=i->on(isodd(i) ? w2 : 1)) + end + end + end + + if nprocs() >= 3 + @testset "passed by value across memory spaces, hierarchical=$hierarchical" for hierarchical in (false, true) + w1, w2 = workers()[1], workers()[2] + test_noaliasing_by_value(; hierarchical, src_scope=on(w1), dst_scope=on(w2)) + test_noaliasing_by_value(; hierarchical, src_scope=on(w1), dst_scope=on(1)) + end + @testset "unkeyed copies are freed, hierarchical=$hierarchical" for hierarchical in (false, true) + w1, w2 = workers()[1], workers()[2] + test_noaliasing_copy_freed(; hierarchical, src_scope=on(w1), dst_scope=on(w2)) + test_noaliasing_copy_freed(; hierarchical, src_scope=on(w1), dst_scope=on(1)) + test_noaliasing_copy_freed(; hierarchical, src_scope=on(w1), dst_scope=on(w2), + mk=noalias_view_tiles, reader=noalias_view_keep!) + test_noaliasing_returns(; hierarchical, src_scope=on(w1), dst_scope=on(w2)) + test_noaliasing_returns(; hierarchical, src_scope=on(w1), dst_scope=on(1)) + end + end + + @testset "unkeyed slot construction" begin + accel = Dagger.current_acceleration() + backing = Dagger.tochunk(Dagger.AliasedObjectCacheStore(accel)) + x = Dagger.tochunk(noalias_val(1)) + space = Dagger.memory_space(x) + # In its own space the value is its own slot, never a copy: a copy + # there would not be copied back after a write. + cache = Dagger.AliasedObjectCache(accel, space, backing) + @test Dagger.aliased_object!(_->error("copied an in-place value"), cache, x) === x + # Elsewhere, a copy made in the wrong space is caught, as on the + # cached path. + if nprocs() >= 2 + other = Dagger.CPURAMMemorySpace(workers()[1]) + other_cache = Dagger.AliasedObjectCache(accel, other, backing) + @test_throws AssertionError Dagger.aliased_object!( + _->Dagger.tochunk(noalias_val(2)), other_cache, x) + + # A copy is recorded for freeing at region end; the argument's own + # payload, should a move ever hand it back, never is. + store = Dagger.unwrap(backing) + proc = first(Dagger.processors(other)) + y = Dagger.aliased_object!(_->Dagger.tochunk(Dagger.unwrap(x), proc, other), other_cache, x) + @test Dagger.unwrap(y) === Dagger.unwrap(x) + @test isempty(store.keys) + y = Dagger.aliased_object!(_->Dagger.tochunk(noalias_val(1), proc, other), other_cache, x) + @test only(store.keys) isa Dagger.CopyKey + @test store.values[other][only(store.keys)] === y + end + end +end + # Custom scheduler tests struct DummyErrorScheduler <: Dagger.DataDepsScheduler end @@ -1374,7 +1479,7 @@ end for idx in 1:length(_logs[:core]) core_log = _logs[:core][idx] if core_log.category == :add_thunk && core_log.kind == :start && - _logs[:taskfuncnames][idx] == "unsafe_free!" + _logs[:taskfuncnames][idx] in ("unsafe_free!", "free_unkeyed_copy!") push!(free_tids, _logs[:id][idx].thunk_id::Int) end end @@ -1488,7 +1593,7 @@ function count_free_tasks(logs) for idx in 1:length(_logs[:core]) core_log = _logs[:core][idx] if core_log.category == :add_thunk && core_log.kind == :start && - _logs[:taskfuncnames][idx] == "unsafe_free!" + _logs[:taskfuncnames][idx] in ("unsafe_free!", "free_unkeyed_copy!") n += 1 end end diff --git a/test/field_deps_defs.jl b/test/field_deps_defs.jl new file mode 100644 index 000000000..bef14291d --- /dev/null +++ b/test/field_deps_defs.jl @@ -0,0 +1,155 @@ +# Shared test bodies for Datadeps field dependencies (`Deps(x, InOut(:field))`). +# +# An isbits field of a mutable struct is memory inside the struct, so its +# dependency must describe that memory. It used to come out as `NoAliasing` +# (the aliasing of the isbits *value*), so a write from another memory space +# was never copied back, and nothing ordered it against other uses of the field. +# +# Run from test/datadeps.jl (threads / Distributed) and test/mpi/cpu.jl (MPI). +# `writeback_visible` must be false on MPI ranks that do not own the origin, +# whose replica of a bare Julia object is never written back to. + +@everywhere begin + mutable struct FieldBox + value::Int + other::Float64 + v::Vector{Float64} + end + field_set_value!(X::FieldBox, x::Int) = (X.value = x; nothing) + field_set_other!(X::FieldBox, x::Float64) = (X.other = x; nothing) + field_get_value(X::FieldBox) = X.value + field_set_ref!(R::Base.RefValue{Int}, x::Int) = (R[] = x; nothing) + mutable struct ScalarFieldBox + value::Int + other::Float64 + end + field_set_value!(X::ScalarFieldBox, x::Int) = (X.value = x; nothing) + field_get_value(X::ScalarFieldBox) = X.value + function Dagger.move!(::typeof(identity), to_space::Dagger.MemorySpace, + from_space::Dagger.MemorySpace, to::ScalarFieldBox, from::ScalarFieldBox) + to.value = from.value + to.other = from.other + return + end + mutable struct FlexibleFieldBox{T} + value::T + other::Int + end + field_set_value!(X::FlexibleFieldBox, x) = (X.value = x; nothing) + field_get_value(X::FlexibleFieldBox) = X.value + field_get_nested_value(X::Union{Tuple,NamedTuple}) = first(X).value + field_set_nested_value!(X::Union{Tuple,NamedTuple}, value) = (first(X).value = value; nothing) + field_set_ref!(R::Base.RefValue{Any}, x) = (R[] = x; nothing) + function Dagger.move!(::typeof(identity), to_space::Dagger.MemorySpace, + from_space::Dagger.MemorySpace, to::FlexibleFieldBox{T}, from::FlexibleFieldBox{T}) where T + to.value = from.value + to.other = from.other + return + end +end + +function test_reference_field_writes(; scope, reader_scope=scope, writeback_visible=true, hierarchical=nothing) + cases = ((Any, 0, 42), (Real, 0, 42), (Union{Nothing,Int}, nothing, 42), + (String, "before", "after"), (Symbol, :before, :after)) + for (T, initial, replacement) in cases, whole_writer in (false, true) + X = FlexibleFieldBox{T}(initial, 17) + seen = nothing + Dagger.spawn_datadeps(; hierarchical) do + if whole_writer + Dagger.@spawn scope=scope field_set_value!(InOut(X), replacement) + seen = Dagger.@spawn scope=reader_scope field_get_value(Deps(X, In(:value))) + else + Dagger.@spawn scope=scope field_set_value!(Deps(X, InOut(:value)), replacement) + seen = Dagger.@spawn scope=reader_scope field_get_value(In(X)) + end + end + @test fetch(seen) == replacement + if writeback_visible + @test X.value == replacement + @test X.other == 17 + end + end + R = Ref{Any}(0) + Dagger.spawn_datadeps(; hierarchical) do + Dagger.@spawn scope=scope field_set_ref!(Deps(R, InOut(:x)), 42) + end + writeback_visible && @test R[] == 42 +end + +function test_isbits_field_writes(; scope, reader_scope=scope, writeback_visible=true, hierarchical=nothing) + X = FieldBox(0, 0.0, zeros(4)) + R = Ref(0) + seen = nothing + Dagger.spawn_datadeps(; hierarchical) do + Dagger.@spawn scope=scope field_set_value!(Deps(X, InOut(:value)), 42) + # A different field of the same object: copied back on its own. + Dagger.@spawn scope=scope field_set_other!(Deps(X, Out(:other)), 1.5) + Dagger.@spawn scope=scope field_set_ref!(Deps(R, InOut(:x)), 42) + # Ordered after the write to the same field. + seen = Dagger.@spawn scope=reader_scope field_get_value(Deps(X, In(:value))) + end + @test fetch(seen) == 42 + if writeback_visible + @test X.value == 42 + @test X.other == 1.5 + @test R[] == 42 + end + + # A field overlaps the parent, in either access order. Callers place the + # writer and reader independently to exercise copies between spaces. + for whole_writer in (false, true) + X = ScalarFieldBox(0, 0.0) + Dagger.spawn_datadeps(; hierarchical) do + if whole_writer + Dagger.@spawn scope=scope field_set_value!(InOut(X), 42) + seen = Dagger.@spawn scope=reader_scope field_get_value(Deps(X, In(:value))) + else + Dagger.@spawn scope=scope field_set_value!(Deps(X, InOut(:value)), 42) + seen = Dagger.@spawn scope=reader_scope field_get_value(In(X)) + end + end + @test fetch(seen) == 42 + writeback_visible && @test X.value == 42 + end +end + +function test_nested_field_remainders() + # An immutable wrapper's spans can reach a mutable child's reference slot. + X = FlexibleFieldBox{Any}("before", 17) + wrapped = (X,) + @test Dagger.remainder_needs_fields(typeof(wrapped)) + spans = Dagger.memory_spans(Dagger.field_aliasing(X, :value)) + payload = Dagger.gather_field_remainder(wrapped, spans) + @test all(iszero, payload.bytes) + @test only(payload.values).second == "before" + # Round-trip the actual payload, rather than copying process-local pointer + # bytes. Scatter into a separate object while preserving its other field. + buffer = IOBuffer() + Dagger.serialize(buffer, payload) + seekstart(buffer) + received = Dagger.deserialize(buffer) + Y = FlexibleFieldBox{Any}("destination", 23) + dest_spans = Dagger.memory_spans(Dagger.field_aliasing(Y, :value)) + Dagger.scatter_field_remainder!((Y,), received, dest_spans) + @test Y.value == "before" + @test Y.other == 23 +end + +function test_nested_field_writes(; scope, reader_scope=scope, writeback_visible=true, hierarchical=nothing) + for named in (false, true), whole_writer in (false, true) + X = FlexibleFieldBox{Any}("before", 17) + wrapped = named ? (; box=X) : (X,) + seen = nothing + Dagger.spawn_datadeps(; hierarchical) do + if whole_writer + Dagger.@spawn scope=scope field_set_nested_value!(InOut(wrapped), "nested") + seen = Dagger.@spawn scope=reader_scope field_get_value(Deps(X, In(:value))) + else + Dagger.@spawn scope=scope field_set_value!(Deps(X, InOut(:value)), "nested") + seen = Dagger.@spawn scope=reader_scope field_get_nested_value(In(wrapped)) + end + end + @test fetch(seen) == "nested" + writeback_visible && @test X.value == "nested" + end +end diff --git a/test/gpu.jl b/test/gpu.jl index 94f81e1d8..a7a771206 100644 --- a/test/gpu.jl +++ b/test/gpu.jl @@ -14,6 +14,13 @@ end include(joinpath(@__DIR__, "array", "sparse_defs.jl")) include(joinpath(@__DIR__, "array", "linalg", "matvec_defs.jl")) include(joinpath(@__DIR__, "gpu_distributed.jl")) +include(joinpath(@__DIR__, "noaliasing_gpu_defs.jl")) + +@testset "NoAliasing device arguments ($name)" for (name, scope) in GPU_SCOPES + cpu_proc = first(filter(p -> p isa Dagger.ThreadProc, + collect(Dagger.get_processors(Dagger.OSProc())))) + test_noaliasing_gpu(; src_scope=Dagger.ExactScope(cpu_proc), dst_scope=scope) +end @testset "Dense matvec ($name)" for (name, scope) in GPU_SCOPES Dagger.with_options(; scope) do diff --git a/test/mpi/cpu.jl b/test/mpi/cpu.jl index e950e75de..3d7290118 100644 --- a/test/mpi/cpu.jl +++ b/test/mpi/cpu.jl @@ -44,6 +44,8 @@ const MPIExt = Base.get_extension(Dagger, :MPIExt) include(joinpath(@__DIR__, "..", "util.jl")) include(joinpath(@__DIR__, "..", "array", "stencil_defs.jl")) include(joinpath(@__DIR__, "..", "array", "sparse_defs.jl")) +include(joinpath(@__DIR__, "..", "field_deps_defs.jl")) +@testset "Nested field remainder payload" test_nested_field_remainders() Dagger.accelerate!(:mpi) Dagger.check_uniformity!(true) @@ -779,6 +781,16 @@ end end end +@testset "Isbits field dependencies, hierarchical=$hierarchical" for hierarchical in (false, true) + # Shared with test/datadeps.jl; see test/field_deps_defs.jl + r1 = min(1, nranks-1) + test_isbits_field_writes(; hierarchical, scope=rank_scope(0), writeback_visible = rank == 0) + test_isbits_field_writes(; hierarchical, scope=rank_scope(r1), writeback_visible = rank == 0) + test_isbits_field_writes(; hierarchical, scope=rank_scope(r1), reader_scope=rank_scope(nranks-1), writeback_visible = rank == 0) + test_reference_field_writes(; hierarchical, scope=rank_scope(r1), reader_scope=rank_scope(0), writeback_visible = rank == 0) + test_nested_field_writes(; hierarchical, scope=rank_scope(r1), reader_scope=rank_scope(0), writeback_visible = rank == 0) +end + @testset "Field aliasing" begin # Symbol dep_mods narrow the dependency (and cross-rank move!) to one # field of a wrapped object (mirrors test/datadeps.jl "Field aliasing") diff --git a/test/mpi/gpu_suite.jl b/test/mpi/gpu_suite.jl index 3455a28f4..aa23e69e5 100644 --- a/test/mpi/gpu_suite.jl +++ b/test/mpi/gpu_suite.jl @@ -40,6 +40,7 @@ include(joinpath(@__DIR__, "..", "util.jl")) include(joinpath(@__DIR__, "..", "array", "stencil_defs.jl")) include(joinpath(@__DIR__, "..", "array", "sparse_defs.jl")) include(joinpath(@__DIR__, "..", "array", "linalg", "matvec_defs.jl")) +include(joinpath(@__DIR__, "..", "noaliasing_gpu_defs.jl")) # Broadcast-only mutation helpers (scalar indexing is illegal on GPU arrays) add1!(X) = (X .+= 1; nothing) @@ -97,6 +98,10 @@ function run_mpi_gpu_suite(cfg) mixed_scope() = Dagger.UnionScope(vcat([cpu_scope(r) for r in 0:nranks-1], [gpu_scope(r) for r in 0:nranks-1])...) + @testset "NoAliasing host-to-device arguments ($(cfg.name))" begin + test_noaliasing_gpu(; src_scope=cpu_scope(0), dst_scope=gpu_scope(min(1, nranks-1))) + end + # `Dagger.scope(; =1)` composed with `mpi_rank`/`worker` (or, with # neither, dispatched via the active `:mpi` acceleration) should reproduce # the scopes built manually above. diff --git a/test/mpi/noaliasing_args.jl b/test/mpi/noaliasing_args.jl index df7077903..945e663a0 100644 --- a/test/mpi/noaliasing_args.jl +++ b/test/mpi/noaliasing_args.jl @@ -1,23 +1,45 @@ -# Datadeps arguments whose aliasing is `NoAliasing` share one aliasing identity; each must still reach its own task -# (app entry 45: with several in flight, writer i received the value of another partition). -struct NoAliasVal; part::Int; v::Vector{Float64}; end -Dagger.aliasing(::NoAliasVal) = Dagger.NoAliasing() -mk_noalias(part::Int) = NoAliasVal(part, fill(Float64(part), 10 + part)) -check_noalias!(buf::Vector{Float64}, x::NoAliasVal, expect::Int) = (buf[1] = x.part == expect ? 0.0 : 1.0; buf[2] = x.part; nothing) +# Datadeps arguments whose aliasing describes no memory must each reach their +# task with their own value, both on the rank that created them and on another +# rank. The bodies are shared with test/datadeps.jl; see test/noaliasing_defs.jl. -@testset "NoAliasing arguments of one Datadeps region keep their own value" begin - nr = MPI.Comm_size(comm) - P = 2 * nr - owner_of(i) = (i - 1) ÷ 2 - procs_by_rank = Dict(r => first(filter(p -> p.rank == r, mpi_procs())) for r in 0:nr-1) - bufs = [Dagger.tochunk(zeros(2), procs_by_rank[owner_of(i)], Dagger.memory_space(procs_by_rank[owner_of(i)])) for i in 1:P] - vals = [Dagger.@spawn(scope=Dagger.scope(mpi_rank=owner_of(i)), mk_noalias(i)) for i in 1:P] - Dagger.spawn_datadeps() do - for i in 1:P - Dagger.@spawn scope=Dagger.scope(mpi_rank=owner_of(i)) check_noalias!(Dagger.InOut(bufs[i]), vals[i], i) +include(joinpath(@__DIR__, "..", "noaliasing_defs.jl")) +@testset "Bounded escaped-storage inspection" test_noaliasing_retention_budget() +@testset "Pending handles retain escaped storage" test_noaliasing_pending_handles() + +@testset "NoAliasing Arguments" begin + # Two values per rank, so that distinct values meet in one memory space. + owner(i) = (i - 1) % nranks + on(r) = Dagger.scope(mpi_rank=r) + nvals = 2 * nranks + @testset "$(nameof(mk)), hierarchical=$hierarchical" for mk in (noalias_val, noalias_wrap), hierarchical in (false, true) + @testset "write access is rejected" begin + test_noaliasing_write_rejected(; mk, hierarchical, scope=on(0)) + end + mk === noalias_val && @testset "write access to an immutable isbits field is rejected" begin + test_immutable_field_write_rejected(; hierarchical, scope=on(0)) + end + @testset "in place" begin + test_noaliasing_args(; mk, hierarchical, nvals, + src_scope=i->on(owner(i)), + dst_scope=i->on(owner(i))) + end + if nranks > 1 + @testset "across ranks" begin + test_noaliasing_args(; mk, hierarchical, nvals, + src_scope=i->on(owner(i)), + dst_scope=i->on((owner(i) + 1) % nranks)) + end + end + end + if nranks > 1 + @testset "passed by value across ranks, hierarchical=$hierarchical" for hierarchical in (false, true) + test_noaliasing_by_value(; hierarchical, src_scope=on(0), dst_scope=on(1)) + end + @testset "unkeyed copies are freed, hierarchical=$hierarchical" for hierarchical in (false, true) + test_noaliasing_copy_freed(; hierarchical, src_scope=on(0), dst_scope=on(1)) + test_noaliasing_copy_freed(; hierarchical, src_scope=on(0), dst_scope=on(1), + mk=noalias_view_tiles, reader=noalias_view_keep!) + test_noaliasing_returns(; hierarchical, src_scope=on(0), dst_scope=on(1)) end end - seen = [fetch(Dagger.@spawn(scope=Dagger.scope(mpi_rank=owner_of(i)), copy(bufs[i]))) for i in 1:P] - @test all(s -> s[1] == 0.0, seen) - @test [Int(s[2]) for s in seen] == collect(1:P) end diff --git a/test/noaliasing_defs.jl b/test/noaliasing_defs.jl new file mode 100644 index 000000000..8cb531625 --- /dev/null +++ b/test/noaliasing_defs.jl @@ -0,0 +1,268 @@ +# Shared test bodies for Datadeps arguments whose aliasing describes no memory. +# +# Datadeps normally shares one slot per memory space between arguments whose +# aliasing compares equal, which is how overlapping views end up backed by one +# copy. An argument whose aliasing describes no memory has nothing to share, and +# its aliasing carries no identity either: every `NoAliasing()` compares equal, +# as does every empty `CombinedAliasing` (a struct whose fields all report +# `NoAliasing`). Keyed on that, a second distinct argument used in the same +# space was silently handed the first one's value. +# +# The slot logic is core Datadeps code, shared by every acceleration, so these +# bodies run from each entry point: +# +# threads / Distributed -> test/datadeps.jl +# MPI -> test/mpi/noaliasing_args.jl (from test/mpi/cpu.jl) +# +# `src_scope(i)` places the task that creates value `i`, and `dst_scope(i)` the +# task that reads it. Equal scopes exercise the in-place path, where the slot is +# the value itself; different memory spaces exercise the path that copies the +# value into a slot of its own. + +@everywhere begin + # Declared `NoAliasing` although it holds a `Vector`: the user's way of + # saying it shares no memory with anything else. `type_may_alias` still + # answers `true` (it inspects field types), so these values do reach + # Datadeps' slot machinery. + struct NoAliasVal + v::Vector{Float64} + end + Dagger.aliasing(::NoAliasVal) = Dagger.NoAliasing() + + # Aliasing is computed from the fields, which all report `NoAliasing`, so + # the result is an empty `CombinedAliasing`. + struct NoAliasWrap + x::NoAliasVal + end + + # Such an argument is read-only and passed by value: its slot in another + # space is `move`'s copy, and nothing is ever copied into it afterwards. + # Fail loudly if Datadeps tries. + noalias_no_copy(T) = error("Datadeps copied into a `$T` argument, whose aliasing describes no memory") + Dagger.move!(dep_mod, to_space::Dagger.MemorySpace, from_space::Dagger.MemorySpace, + to::NoAliasVal, from::NoAliasVal) = noalias_no_copy(NoAliasVal) + Dagger.move!(dep_mod, to_space::Dagger.MemorySpace, from_space::Dagger.MemorySpace, + to::NoAliasWrap, from::NoAliasWrap) = noalias_no_copy(NoAliasWrap) + + # Each value is distinguishable by both content and length. + noalias_val(i::Int) = NoAliasVal(fill(Float64(i), 10 + i)) + noalias_wrap(i::Int) = NoAliasWrap(noalias_val(i)) + noalias_id(x::NoAliasVal) = (Int(x.v[1]), length(x.v)) + noalias_id(x::NoAliasWrap) = noalias_id(x.x) +end + +# Every task of one region must read its own argument's value. +function test_noaliasing_args(; mk, src_scope, dst_scope, nvals::Int=4, hierarchical=nothing) + vals = [Dagger.@spawn scope=src_scope(i) mk(i) for i in 1:nvals] + ids = Vector{Dagger.DTask}(undef, nvals) + Dagger.spawn_datadeps(; hierarchical) do + for i in 1:nvals + ids[i] = Dagger.@spawn scope=dst_scope(i) noalias_id(In(vals[i])) + end + end + @test [fetch(ids[i]) for i in 1:nvals] == [(i, 10 + i) for i in 1:nvals] +end + +# An isbits `Array` declared `NoAliasing`. Unlike the values above, Datadeps +# could leave such a slot uninitialized, for a later copy task to fill: the +# reader would not wait for that copy, since nothing orders tasks on aliasing +# that describes no memory. And Datadeps can free its copies eagerly (they are +# Libc-backed), so these also check that a copy made outside the aliased-object +# cache is freed at region end -- and not before every task reading it is done. +@everywhere begin + struct NoAliasTile + a::Float64 + b::Int + end + Dagger.aliasing(::Vector{NoAliasTile}) = Dagger.NoAliasing() + Dagger.move!(dep_mod, to_space::Dagger.MemorySpace, from_space::Dagger.MemorySpace, + to::Vector{NoAliasTile}, from::Vector{NoAliasTile}) = + noalias_no_copy(Vector{NoAliasTile}) + noalias_tiles(n::Int) = [NoAliasTile(i, i) for i in 1:n] + noalias_view_tiles(n::Int) = view(noalias_tiles(n), 2:n-1) + noalias_sum(x::Vector{NoAliasTile}) = sum(t->t.b, x) + noalias_return_input(x) = x + noalias_return_view(x) = view(x, :) + noalias_return_nested(x) = (x,) + noalias_returned_storage(x::Tuple) = noalias_returned_storage(first(x)) + noalias_returned_storage(x::SubArray) = noalias_returned_storage(parent(x)) + noalias_returned_storage(x) = x + + # Readers hold on to the slot they were given, after checking that it was + # not freed while they ran. + const NOALIAS_SEEN = Vector{Any}() + const NOALIAS_SEEN_LOCK = ReentrantLock() + noalias_copy_buffer(x::SubArray) = noalias_copy_buffer(parent(x)) + noalias_copy_buffer(x) = x + function noalias_keep!(x) + sleep(0.25) + @lock NOALIAS_SEEN_LOCK push!(NOALIAS_SEEN, x) + return Dagger.is_libc_allocated(noalias_copy_buffer(x)) + end + function noalias_view_keep!(x) + @assert sum(t -> t.b, x) == 27 + return noalias_keep!(x) + end + function noalias_seen_freed() + @lock NOALIAS_SEEN_LOCK begin + freed = !isempty(NOALIAS_SEEN) && !any(x -> Dagger.is_libc_allocated(noalias_copy_buffer(x)), NOALIAS_SEEN) + empty!(NOALIAS_SEEN) + return freed + end + end +end + +function test_noaliasing_returns(; src_scope, dst_scope, hierarchical=nothing) + for returner in (noalias_return_input, noalias_return_view, noalias_return_nested) + input = Dagger.@spawn scope=src_scope noalias_tiles(8) + result = nothing + Dagger.spawn_datadeps(; hierarchical) do + result = Dagger.spawn(returner, Dagger.Options(; scope=dst_scope), In(input)) + end + # The returned value owns the copy now, including through a view or a + # returned container. Region cleanup must leave it valid to serialize. + actual = fetch(result) + @test noalias_sum(noalias_returned_storage(actual)) == 36 + end +end + +# +# `freeable=false` is for transports whose copies are ordinary GC-managed +# arrays, which there is nothing to free eagerly; it then only checks that +# nothing is left allocated. +function test_noaliasing_copy_freed(; src_scope, dst_scope, nreaders::Int=2, freeable::Bool=true, hierarchical=nothing, + mk=noalias_tiles, reader=noalias_keep!) + v = Dagger.@spawn scope=src_scope mk(8) + kept = Vector{Dagger.DTask}(undef, nreaders) + Dagger.spawn_datadeps(; hierarchical) do + for i in 1:nreaders + kept[i] = Dagger.@spawn scope=dst_scope reader(In(v)) + end + end + # Each reader got a freeable copy, which was still allocated while it ran... + freeable && @test all(i->fetch(kept[i]), 1:nreaders) + # ...and freed once the region ended. + @test fetch(Dagger.@spawn scope=dst_scope noalias_seen_freed()) +end + +# The slot a reader in another space gets is a complete copy from the start. +function test_noaliasing_by_value(; src_scope, dst_scope, n::Int=1_000_000, nregions::Int=3, hierarchical=nothing) + for _ in 1:nregions + v = Dagger.@spawn scope=src_scope noalias_tiles(n) + total = nothing + Dagger.spawn_datadeps(; hierarchical) do + total = Dagger.@spawn scope=dst_scope noalias_sum(In(v)) + end + @test fetch(total) == sum(1:n) + end +end + +# Such an argument is read-only, so asking to write it is an error rather than +# a write that would silently be lost. +function test_noaliasing_write_rejected(; mk, scope, hierarchical=nothing) + x = Dagger.@spawn scope=scope mk(1) + for dep in (Out, InOut) + @test_throws ArgumentError Dagger.spawn_datadeps(; hierarchical) do + Dagger.@spawn scope=scope noalias_id(dep(x)) + end + end +end + +# The same holds for an isbits field of an immutable struct, which describes no +# memory and cannot be written at all. +@everywhere begin + struct NoAliasImmutableBox + value::Int + v::Vector{Float64} + end + noalias_touch(x) = nothing +end +function test_immutable_field_write_rejected(; scope, hierarchical=nothing) + B = NoAliasImmutableBox(0, zeros(2)) + @test_throws ArgumentError Dagger.spawn_datadeps(; hierarchical) do + Dagger.@spawn scope=scope noalias_touch(Deps(B, InOut(:value))) + end +end + +@everywhere begin + struct NoAliasRetentionNode + left::Any + right::Any + end + function noalias_retention_dag(n) + root = nothing + for _ in 1:n + root = NoAliasRetentionNode(root, root) + end + return root + end +end +function test_noaliasing_retention_budget() + payload = noalias_tiles(8) + @test !Dagger.retains_unkeyed_storage((1, :unrelated, nothing), payload) + @test Dagger.retains_unkeyed_storage(view(payload, :), payload) + # Only 22 unique nodes, but an unbounded recursive walk unfolds 2^23-1. + # This size still finishes promptly if the work bound regresses. + @test Dagger.retains_unkeyed_storage(noalias_retention_dag(22), payload) + cycle = Any[nothing] + cycle[1] = cycle + @test Dagger.retains_unkeyed_storage(cycle, payload) + # Every child fits individually, but their combined inspection is bounded. + siblings = ntuple(_ -> noalias_retention_dag(5), 5) + @test Dagger.retains_unkeyed_storage(siblings, payload) + @test Dagger.retains_unkeyed_storage(Vector{Any}(undef, 1000), payload) + @test Dagger.retains_unkeyed_storage(noalias_retention_dag(22), noalias_retention_dag(22)) +end + +@everywhere begin + mutable struct NoAliasOpaqueHolder + key::UInt + end + const NOALIAS_OPAQUE_ROOTS = Dict{UInt,Any}() +end + +@everywhere function noalias_pending_return(payload, started, gate) + notify(started) + Dagger.Sch.thunk_yield() do + wait(gate) + end + return payload +end + +function test_noaliasing_pending_handles() + # This local graph uses the Distributed backend on every MPI rank too: + # asynchronous handles are inspected without collective fetches or waits. + Dagger.with_options(; acceleration=Dagger.DistributedAcceleration()) do + payload = Dagger.alloc_libc_array(NoAliasTile, 8) + fill!(payload, NoAliasTile(1.0, 1)) + started = Base.Event() + gate = Base.Event() + child = Dagger.@spawn scope=Dagger.scope(worker=1) noalias_pending_return(payload, started, gate) + holder = NoAliasOpaqueHolder(UInt(0)) + holder.key = objectid(holder) + NOALIAS_OPAQUE_ROOTS[holder.key] = payload + try + wait(started) + @test !istaskdone(child) + @test Dagger.retains_unkeyed_storage(child, payload) + @test Dagger.retains_unkeyed_storage((child,), payload) + @test Dagger.retains_unkeyed_storage((holder,), payload) + @test NOALIAS_OPAQUE_ROOTS[holder.key] === payload + ref = Dagger.MemPool.poolset(payload) + @test Dagger.retains_unkeyed_storage((ref,), payload) + future = Dagger.ThunkFuture() + @test Dagger.retains_unkeyed_storage(future, payload) + @test Dagger.retains_unkeyed_storage(future.future, payload) + @static if isdefined(Dagger.MemPool, :DFuture) && isdefined(Dagger.MemPool, :DEvent) + @test Dagger.retains_unkeyed_storage(future.future.event, payload) + end + put!(future, payload) + @test fetch(future; move_value=false) === payload + finally + delete!(NOALIAS_OPAQUE_ROOTS, holder.key) + notify(gate) + @test fetch(child) === payload + Dagger.unsafe_free!(payload) + end + end +end diff --git a/test/noaliasing_gpu_defs.jl b/test/noaliasing_gpu_defs.jl new file mode 100644 index 000000000..a9cb49f79 --- /dev/null +++ b/test/noaliasing_gpu_defs.jl @@ -0,0 +1,110 @@ +# Shared NoAliasing host-to-device copy/lifetime checks, called by test/gpu.jl +# and test/mpi/gpu_suite.jl. Int32/Float32 keeps the payload portable to Metal +# and devices without Float64 support. +@everywhere begin + struct NoAliasGPUTile + value::Int32 + other::Float32 + end + Dagger.aliasing(::Vector{NoAliasGPUTile}) = Dagger.NoAliasing() + noalias_gpu_tiles(n) = [NoAliasGPUTile(Int32(i), Float32(i)) for i in 1:n] + const NOALIAS_GPU_TYPES = Set{Type}() + const NOALIAS_GPU_FREES = Threads.Atomic{Int}(0) + const NOALIAS_GPU_FREED = Set{UInt64}() + const NOALIAS_GPU_LOCK = ReentrantLock() + + function noalias_gpu_substitute(ex, T, wrapper) + ex === :NOALIAS_GPU_ARRAY && return T + ex === :NOALIAS_GPU_WRAPPER && return wrapper + if ex isa Expr + for i in eachindex(ex.args) + ex.args[i] = noalias_gpu_substitute(ex.args[i], T, wrapper) + end + end + return ex + end + function install_noalias_gpu_type!(T) + T in NOALIAS_GPU_TYPES && return + push!(NOALIAS_GPU_TYPES, T) + wrapper = Base.typename(T).wrapper + methods = quote + # The host type alone declares the by-value contract. Conversion + # to a device array must not introduce a delayed copy-in. + function Dagger.move!(::typeof(identity), ::Dagger.MemorySpace, + ::Dagger.MemorySpace, ::NOALIAS_GPU_ARRAY, + ::AbstractVector{NoAliasGPUTile}) + error("NoAliasing device slot received a delayed copy-in") + end + function Dagger.unsafe_free!(x::NOALIAS_GPU_ARRAY) + key = UInt64(Dagger.data_address(x)) + lock(NOALIAS_GPU_LOCK) do + push!(NOALIAS_GPU_FREED, key) + end + Threads.atomic_add!(NOALIAS_GPU_FREES, 1) + # Invoke the backend's ordinary array method, not this more + # specific test-element method. + invoke(Dagger.unsafe_free!, Tuple{NOALIAS_GPU_WRAPPER}, x) + end + end + Core.eval(@__MODULE__, noalias_gpu_substitute(methods, T, wrapper)) + return + end + function noalias_gpu_reset_freed!() + lock(NOALIAS_GPU_LOCK) do + empty!(NOALIAS_GPU_FREED) + end + return NOALIAS_GPU_FREES[] + end + noalias_gpu_frees() = NOALIAS_GPU_FREES[] + function noalias_gpu_all_freed(keys) + lock(NOALIAS_GPU_LOCK) do + return all(key -> key in NOALIAS_GPU_FREED, keys) + end + end + function noalias_gpu_read(x) + key = UInt64(Dagger.data_address(x)) + sleep(0.01) + live = lock(NOALIAS_GPU_LOCK) do + !(key in NOALIAS_GPU_FREED) + end + total = live ? mapreduce(t -> t.value, +, x; init=Int32(0)) : Int32(-1) + return total, length(x), key, live + end +end + +function test_noaliasing_gpu(; src_scope, dst_scope) + # Query the value's actual device type, including under MPI where the + # Chunk's logical type can deliberately remain its host source type. + T = fetch(Dagger.@spawn scope=dst_scope typeof(noalias_gpu_tiles(1))) + @test T <: Dagger.GPUArraysCore.AbstractGPUArray + @everywhere install_noalias_gpu_type!($T) + # The planner and old processor runners must see the newly installed hook. + Dagger.with_options(; scope=Dagger.UnionScope(src_scope, dst_scope)) do + Base.invokelatest(test_noaliasing_gpu_body; src_scope, dst_scope) + end +end +function test_noaliasing_gpu_body(; src_scope, dst_scope) + for hierarchical in (false, true) + @testset "by-value device copies hierarchical=$hierarchical" begin + before = fetch(Dagger.@spawn scope=dst_scope noalias_gpu_reset_freed!()) + input = Dagger.@spawn scope=src_scope noalias_gpu_tiles(32) + readers = Dagger.DTask[] + Dagger.spawn_datadeps(; hierarchical) do + for _ in 1:2 + push!(readers, Dagger.@spawn scope=dst_scope noalias_gpu_read(In(input))) + end + end + results = fetch.(readers) + @test all(r -> r[1] == 528 && r[2] == 32 && r[4], results) + keys = Tuple(r[3] for r in results) + @test fetch(Dagger.@spawn scope=dst_scope noalias_gpu_all_freed(keys)) + after = fetch(Dagger.@spawn scope=dst_scope noalias_gpu_frees()) + @test after - before == length(unique(keys)) + for dep in (Out, InOut) + @test_throws ArgumentError Dagger.spawn_datadeps(; hierarchical) do + Dagger.@spawn scope=dst_scope noalias_gpu_read(dep(input)) + end + end + end + end +end