diff --git a/AGENTS.md b/AGENTS.md index aaf8fe06a..00d880fe3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1172,3 +1172,19 @@ this section verbatim). Each entry is one bullet starting with `- `. and without it precompilation fails with "Task cannot be serialized". The precompile workload now waits for the interrupted tasks and empties the list itself. + +107. **A wrapper lives in the host memory space unless something says + otherwise, and may share its parent's aliasing.** `memory_space` has + methods for device arrays, not for `Transpose`, `Adjoint` or a `SubArray` + of one, so `transpose(X)` of a `CuArray` is a host-space argument whose + `aliasing` is exactly `X`'s. Datadeps' aliased-object cache keys slots by + aliasing and records a key's original in the space where it is *first* + 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 + asking for `InOut(A)` on another worker, after one reading + `In(transpose(A))`, receives a `Transpose`, and its write lands + 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. diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index aa068553a..eb132d27f 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2283,8 +2283,8 @@ end # The aliased-object cache is a per-rank replicated store; every rank updates # its own copy at the same logical point during SPMD planning, so no # cross-rank communication is required here. -function set_stored!(accel::MPIAcceleration, cache::AliasedObjectCache, value::Chunk, ainfo::AbstractAliasing) - set_stored!(unwrap(cache.chunk)::AliasedObjectCacheStore, cache.space, value, ainfo) +function set_stored!(accel::MPIAcceleration, cache::AliasedObjectCache, value::Chunk, ainfo::AbstractAliasing, original::Bool=false) + set_stored!(unwrap(cache.chunk)::AliasedObjectCacheStore, cache.space, value, ainfo, original) return end function set_key_stored!(accel::MPIAcceleration, cache::AliasedObjectCache, space::MemorySpace, ainfo::AbstractAliasing, value::Chunk) diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index a27d4de49..3fd0cda8c 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -434,8 +434,10 @@ struct AliasedObjectCacheStore # The `(space, key)` pairs identifying the user's original data, as opposed # to Datadeps-allocated copies. A `key` ainfo is recorded here at the space # where it is first registered (its source space, see `set_key_stored!`), - # which is exactly where its value is the user's own object. Every *other* - # space holding that key is a copy we allocated and may free. + # which is exactly where its value is the user's own object -- and at any + # other space whose slot turned out to be the user's object as well (see + # `slot_holds_value`). Every other space holding that key is a copy we + # allocated and may free. originals::Set{Tuple{MemorySpace,AbstractAliasing}} # Copies whose own (destination-side) ainfo has not been computed yet, as # `key => copy`. See `resolve_pending!`. @@ -516,8 +518,9 @@ end is_original(cache, space, ainfo) -> Bool Whether `cache.values[space][ainfo]` holds the user's original data (which must -never be freed) rather than a Datadeps-allocated copy. True only at the `key` -ainfo's source space (recorded by `set_key_stored!`). +never be freed) rather than a Datadeps-allocated copy. True at the `key` ainfo's +source space (recorded by `set_key_stored!`), and at any other space whose slot +is the user's own object (recorded by `set_stored!`; see `slot_holds_value`). """ is_original(cache::AliasedObjectCacheStore, space::MemorySpace, ainfo::AbstractAliasing) = (space, ainfo) in cache.originals @@ -538,11 +541,19 @@ function get_stored(cache::AliasedObjectCacheStore, space::MemorySpace, ainfo::A @assert key !== nothing "Cache does not have derived ainfo $ainfo" return cache.values[space][key] end -function set_stored!(cache::AliasedObjectCacheStore, dest_space::MemorySpace, value::Chunk, ainfo::AbstractAliasing) +# `original` marks `value` as the user's own object rather than a copy (see +# `slot_holds_value`): it is then never freed, and needs no destination-side +# ainfo of its own, since its memory is the key's. +function set_stored!(cache::AliasedObjectCacheStore, dest_space::MemorySpace, value::Chunk, ainfo::AbstractAliasing, original::Bool=false) @assert !is_stored(cache, dest_space, ainfo) "Cache already has derived ainfo $ainfo" @check_uniform(value) + @check_uniform(original) key = cache.derived[ainfo] - push!(cache.pending, key => value) + if original + push!(cache.originals, (dest_space, key)) + else + push!(cache.pending, key => value) + end push!(get!(Set{AbstractAliasing}, cache.stored, dest_space), key) values_dict = get!(Dict{AbstractAliasing,Chunk}, cache.values, dest_space) values_dict[key] = value @@ -615,13 +626,13 @@ function get_stored(cache::AliasedObjectCache, ainfo::AbstractAliasing) return get_stored(cache_raw, cache.space, ainfo) end -function set_stored!(accel::DistributedAcceleration, cache::AliasedObjectCache, value::Chunk, ainfo::AbstractAliasing) +function set_stored!(accel::DistributedAcceleration, cache::AliasedObjectCache, value::Chunk, ainfo::AbstractAliasing, original::Bool=false) wid = root_worker_id(cache.chunk) if wid != myid() - return remotecall_fetch(set_stored!, wid, accel, cache, value, ainfo) + return remotecall_fetch(set_stored!, wid, accel, cache, value, ainfo, original) end cache_raw = unwrap(cache.chunk)::AliasedObjectCacheStore - set_stored!(cache_raw, cache.space, value, ainfo) + set_stored!(cache_raw, cache.space, value, ainfo, original) return end @@ -657,11 +668,49 @@ function aliased_object!(f, cache::AliasedObjectCache, x; ainfo=aliasing(cache.a # the space assertion above already implies it, and asking for `y`'s ainfo # here would cost a collective per slot (see `resolve_pending!`). @assert memory_space(y) == cache.space "Space mismatch! $(memory_space(y)) != $(cache.space)" - set_stored!(cache.accel, cache, y, ainfo) + # Usually `y` is a copy, which the region-end free loop releases. But it + # can be the user's own object: `f` may hand back `x` itself (the + # in-place slot of `generate_slot!`, when another argument with the same + # aliasing was registered first in another space), or `move` may be the + # identity between two spaces of one process. Datadeps frees only what + # it allocated, so record such a slot as an original instead. + set_stored!(cache.accel, cache, y, ainfo, slot_holds_value(cache.accel, x, y)) return y end end +""" + slot_holds_value(accel, x, y::Chunk) -> Bool + +Whether the slot `y` made for `x` holds `x`'s own payload rather than a copy of +it. `move` between two memory spaces normally copies, and `libc_backed` copies +any `Array` it did not allocate -- but it returns an already Libc-backed `Array` +unchanged, so a `move` that is the identity between two spaces of one process +(the default `move` for a user-defined processor, say) would hand back the +user's own object. And a slot that is `x` itself (`y === x`) is the user's +object by construction. Datadeps frees only what it allocated, so such a slot +must not be recorded for freeing. + +`y === x` is decided identically on every rank, as both are the same uniform +`Chunk`. Beyond that, only values in one process can be the same object, so this +compares payloads only when both are local. Under uniform (MPI) execution that +comparison is skipped (`false`): whether a slot is freed must agree across ranks, +and only the rank that owns both payloads could compare them, so the others would +answer differently. This is a uniformity requirement, not a claim that MPI is +safe: a GPU `move` can return its input (a device array already on the target +device), so an identity move under MPI is not ruled out, only left undetected. +""" +function slot_holds_value(accel, x, y::Chunk) + y === x && return true + uniform_execution(accel) && return false + root_worker_id(y) == myid() || return false + if x isa Chunk + root_worker_id(x) == myid() || return false + return unwrap(y) === unwrap(x) + end + return unwrap(y) === x +end + # N.B. Declared `mutable` (despite no field ever being rebound) purely for # identity: an immutable struct this large is re-boxed on every dynamic call # that passes it, and planning threads it through hundreds of such calls per diff --git a/test/datadeps.jl b/test/datadeps.jl index 30944ccf2..6ef798575 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1356,3 +1356,85 @@ end end end end + +# A memory space and processor defined outside Dagger, as the processor docs +# invite. It relies on the default `move`, which is the identity, so a slot made +# in this space for an argument from host memory is the argument itself. +@everywhere begin + struct IdentityMoveSpace <: Dagger.MemorySpace + owner::Int + end + struct IdentityMoveProc <: Dagger.Processor + owner::Int + end + Dagger.get_parent(proc::IdentityMoveProc) = Dagger.OSProc(proc.owner) + Dagger.root_worker_id(space::IdentityMoveSpace) = space.owner + Dagger.memory_spaces(proc::IdentityMoveProc) = Set([IdentityMoveSpace(proc.owner)]) + Dagger.processors(space::IdentityMoveSpace) = Set([IdentityMoveProc(space.owner)]) + Dagger.iscompatible_func(::IdentityMoveProc, opts, f) = true + Dagger.iscompatible_arg(::IdentityMoveProc, opts, x) = true + Dagger.default_enabled(::IdentityMoveProc) = true + Dagger.execute!(::IdentityMoveProc, f, args...) = f(args...) +end + +@testset "Datadeps never frees the user's own object" begin + # Datadeps frees only slots it allocated itself. Each case below makes a + # slot that is the user's object (or holds its payload), in a space other + # than the one its aliasing was first registered in, and checks that the + # cache records it as an original -- which the region-end free loop skips -- + # rather than as a Datadeps-allocated copy. + accel = Dagger.current_acceleration() + here = Dagger.CPURAMMemorySpace(myid()) + there = IdentityMoveSpace(myid()) + proc = IdentityMoveProc(myid()) + new_cache(space) = (backing = Dagger.tochunk(Dagger.AliasedObjectCacheStore(accel)); + (Dagger.AliasedObjectCache(accel, space, backing), Dagger.unwrap(backing))) + + @testset "a move that hands back the argument's payload" begin + x = rand(4) + key = Dagger.aliasing(accel, x, identity) + cache, store = new_cache(there) + y = Dagger.aliased_object!(_->Dagger.tochunk(x, proc, there), cache, x) + @test Dagger.unwrap(y) === x + @test Dagger.is_original(store, there, key) + + # A real copy is still Datadeps' to free + cache, store = new_cache(there) + Dagger.aliased_object!(_->Dagger.tochunk(copy(x), proc, there), cache, x) + @test !Dagger.is_original(store, there, key) + end + + @testset "a slot that is the argument itself" begin + # Two arguments with the same aliasing, labelled in different spaces of + # one process (as `transpose(X)`, which defaults to the host space, and + # a device array `X` are). The second one's in-place slot is itself. + x = rand(4) + x_there = Dagger.tochunk(x, proc, there) + x_here = Dagger.tochunk(x) + key = Dagger.aliasing(accel, x_here, identity) + backing = Dagger.tochunk(Dagger.AliasedObjectCacheStore(accel)) + store = Dagger.unwrap(backing) + Dagger.aliased_object!(Returns(x_there), Dagger.AliasedObjectCache(accel, there, backing), x_there) + y = Dagger.aliased_object!(Returns(x_here), Dagger.AliasedObjectCache(accel, here, backing), x_here) + @test y === x_here + @test Dagger.is_original(store, here, key) + end + + @testset "end to end, with a user-defined processor" begin + # A Libc-backed array is the one host array `unsafe_free!` releases, and + # `libc_backed` passes it through `move_rewrap` unchanged. + Dagger.add_processor_callback!(()->IdentityMoveProc(myid()), :identity_move_proc) + try + A = Dagger.alloc_libc_array(Float64, 4) + fill!(A, 1.0) + Dagger.spawn_datadeps() do + Dagger.@spawn scope=Dagger.ExactScope(proc) (x->(x[1] = 2.0; nothing))(InOut(A)) + end + @test Dagger.is_libc_allocated(A) + @test A == [2.0, 1.0, 1.0, 1.0] + Dagger.unsafe_free!(A) + finally + Dagger.delete_processor_callback!(:identity_move_proc) + end + end +end diff --git a/test/gpu.jl b/test/gpu.jl index 4f19c1d55..8c691f096 100644 --- a/test/gpu.jl +++ b/test/gpu.jl @@ -91,6 +91,24 @@ end end end +@testset "Datadeps never frees a device argument ($name)" for (name, scope) in GPU_SCOPES + # Datadeps frees only slots it allocated itself. `transpose(X)` has `X`'s + # aliasing but defaults to the host memory space, so a host task reading it + # registers `X`'s memory there first. The device task's slot for `X` is then + # `X` itself, which used to be recorded as a copy, and freed at region end. + proc = only(Dagger.compatible_processors(scope)) + host = Dagger.scope(worker=1, thread=1) + X = Dagger.move(Dagger.ThreadProc(1, 1), proc, ones(Float32, 4, 4)) + Dagger.with_options(; scope=Dagger.UnionScope(host, scope)) do + Dagger.spawn_datadeps() do + Dagger.@spawn scope=host size(In(transpose(X))) + Dagger.@spawn scope=scope addarray!(InOut(X)) + end + end + Dagger.gpu_synchronize(proc) + @test Dagger.with_context(()->Array(X), proc) == fill(2f0, 4, 4) +end + function generate_thunks() as = [Dagger.spawn(x->x+1, 1) for i in 1:10] Dagger.spawn((xs...)->[sum(xs)], as...)