Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
189 changes: 176 additions & 13 deletions src/datadeps/aliasing.jl
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,8 @@ function resolve_pending!(cache::AliasedObjectCacheStore)
end
for (i, value_ainfo) in enumerate(batch_ainfos(cache.accel, values, dep_mods))
key, value = entries[i]
cache.derived[value_ainfo] = key
# Copies under a `CopyKey` are never looked up by aliasing.
key isa CopyKey || (cache.derived[value_ainfo] = key)
# Keep `value_ainfo` around: this is the one point where the buffer's own
# aliasing is computed on every rank, and the free loop needs it later.
ainfos_dict = get!(Dict{AbstractAliasing,AbstractAliasing}, cache.value_ainfos, memory_space(value))
Expand Down Expand Up @@ -596,6 +597,43 @@ function set_key_stored!(cache::AliasedObjectCacheStore, space::MemorySpace, ain
return
end

"""
CopyKey(id)

Cache key of a copy made for a value whose aliasing has no identity (see
`aliasing_has_identity`). Never looked up by aliasing, only walked by teardown,
whose free of it waits for every task that used its slot (see `UnkeyedSlots`).
"""
struct CopyKey <: AbstractAliasing
id::Int
end
memory_spans(::CopyKey) = MemorySpan{CPURAMMemorySpace}[]

"""
aliasing_has_identity(ainfo) -> Bool

Whether `ainfo` distinguishes the object it describes from every other object.
`false` for aliasings that compare equal for all values (`NoAliasing`, an empty
`CombinedAliasing`); the object cache cannot key such values by their aliasing.
"""
aliasing_has_identity(::AbstractAliasing) = true
aliasing_has_identity(::NoAliasing) = false
aliasing_has_identity(ca::CombinedAliasing) = any(aliasing_has_identity, ca.sub_ainfos)
aliasing_has_identity(w::AliasingWrapper) = aliasing_has_identity(w.inner)

# Records `value` as a Datadeps-allocated copy under a fresh key. It is not an
# original (so it is freed) and not in `derived` (nothing can look it up).
function set_copy_stored!(cache::AliasedObjectCacheStore, space::MemorySpace, value::Chunk)
@check_uniform(value)
key = CopyKey(length(cache.keys) + 1)
push!(cache.keys, key)
push!(get!(Set{AbstractAliasing}, cache.stored, space), key)
values_dict = get!(Dict{AbstractAliasing,Chunk}, cache.values, space)
values_dict[key] = value
push!(cache.pending, key => value)
return
end

struct AliasedObjectCache
accel::Acceleration
space::MemorySpace
Expand Down Expand Up @@ -636,6 +674,15 @@ function set_stored!(accel::DistributedAcceleration, cache::AliasedObjectCache,
return
end

function set_copy_stored!(cache::AliasedObjectCache, value::Chunk)
wid = root_worker_id(cache.chunk)
if wid != myid()
return remotecall_fetch(set_copy_stored!, wid, cache, value)
end
set_copy_stored!(unwrap(cache.chunk)::AliasedObjectCacheStore, cache.space, value)
return
end

function set_key_stored!(accel::DistributedAcceleration, cache::AliasedObjectCache, space::MemorySpace, ainfo::AbstractAliasing, value::Chunk)
wid = root_worker_id(cache.chunk)
if wid != myid()
Expand All @@ -646,10 +693,12 @@ function set_key_stored!(accel::DistributedAcceleration, cache::AliasedObjectCac
end

function aliased_object!(f, cache::AliasedObjectCache, x; ainfo=aliasing(cache.accel, x, identity))
# `NoAliasing` has no identity: every such value would share one cache key,
# so 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.
(ainfo isa NoAliasing || (ainfo isa AliasingWrapper && ainfo.inner isa NoAliasing)) && return f(x)::Chunk
# An aliasing without identity (`NoAliasing`, an empty `CombinedAliasing`,
# ...) is equal for every value that has it, so it cannot be the cache key:
# 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)
x_space = memory_space(x)
if !is_key_present(cache, x_space, ainfo)
# Preserve the object's memory-space/processor pairing when inserting
Expand Down Expand Up @@ -711,12 +760,57 @@ function slot_holds_value(accel, x, y::Chunk)
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
# task. A mutable struct has a stable heap identity and is passed by pointer
# instead, so those boxes disappear. It is never used as a `Dict` key, so the
# resulting identity-based `hash`/`==` are not observed.
function aliased_object_unkeyed!(f, cache::AliasedObjectCache, x)
x_space = memory_space(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
# already-in-place case. An identity move can also wrap the user's same
# payload in a different Chunk, so check ownership before recording it.
if y !== x && x_space != cache.space
@assert memory_space(y) == cache.space "Space mismatch! $(memory_space(y)) != $(cache.space)"
slot_holds_value(cache.accel, x, y) || set_copy_stored!(cache, y)
end
return y
end

"""
UnkeyedSlots

The slots holding copies recorded under a `CopyKey` (see
`aliased_object_unkeyed!`), and every task that used each of them.

The region-end free loop finds the tasks a buffer's free must wait for through
dependency tracking, and dependency tracking orders nothing on an aliasing without
identity (`get_write_deps!` returns at once for `NoAliasing`). On its own, the
free of such a copy would therefore wait for nothing and race the tasks reading
it. But a `CopyKey` copy is private to the slot whose creation made it (the slot
itself for a leaf argument, or one of a wrapper slot's children), so the tasks
that may touch it are exactly the tasks that used that slot. `generate_slot!`
attributes each copy to its slot, `add_reader!` (which every task touching a
slot passes through, writers and copies included) records the slot's users, and
the free loops add those users to the copy's free syncdeps
(`push_copy_users_syncdeps!`).

Everything here is filled in planning order, which is rank-uniform, so under
uniform (MPI) execution every rank derives the same syncdeps.
"""
struct UnkeyedSlots
# Slot, as stored in `DataDepsState.remote_args` => index into `users`
slot_index::IdDict{Any,Int}
# `CopyKey` id => index into `users` of the slot holding that copy
copy_slot::Dict{Int,Int}
# Per slot, in creation order, the tasks that used it
users::Vector{Vector{DTask}}
end
UnkeyedSlots() = UnkeyedSlots(IdDict{Any,Int}(), Dict{Int,Int}(), Vector{DTask}[])

# N.B. Declared `mutable` purely for identity (only `unkeyed_slots` is ever
# rebound, once, lazily): 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 task. A mutable struct has a stable heap identity and is passed by
# pointer instead, so those boxes disappear. It is never used as a `Dict` key, so
# the resulting identity-based `hash`/`==` are not observed.
mutable struct DataDepsState
# The mapping of original raw argument to its Chunk
# N.B. Values are Chunks, or raw remote handles (e.g. ChunkView under MPI)
Expand Down Expand Up @@ -776,6 +870,15 @@ mutable struct DataDepsState
# The mapping of, for a given memory space, the backing Chunks that an ainfo references
# Used by slot generation to replace the backing Chunks during move
ainfo_backing_chunk::Chunk{AliasedObjectCacheStore}
# The store `ainfo_backing_chunk` holds. That chunk is created here, by the
# planner, so it is always local; holding the store directly lets slot
# generation check it without a MemPool lookup per slot.
ainfo_backing::AliasedObjectCacheStore

# Slots holding `CopyKey` copies, and the tasks using them; see
# `UnkeyedSlots`. `nothing` until a region makes such a copy, so that
# regions without any pay nothing for it.
unkeyed_slots::Union{UnkeyedSlots,Nothing}

# Cache of argument's supports_inplace_move query result
supports_inplace_cache::IdDict{Any,Bool}
Expand Down Expand Up @@ -819,8 +922,9 @@ mutable struct DataDepsState
arg_current = Dict{ArgumentWrapper,Set{MemorySpace}}()
arg_overlaps = Dict{ArgumentWrapper,Set{ArgumentWrapper}}()
accel = current_acceleration()
ainfo_backing = AliasedObjectCacheStore(accel)
ainfo_backing_chunk = _with_default_acceleration() do
tochunk(AliasedObjectCacheStore(accel))
tochunk(ainfo_backing)
end

supports_inplace_cache = IdDict{Any,Bool}()
Expand All @@ -832,7 +936,7 @@ mutable struct DataDepsState
ainfos_owner = Dict{AliasingWrapper,Union{Pair{DTask,Int},Pair{CopyBatchOwner,Int},Nothing}}()
ainfos_readers = Dict{AliasingWrapper,Vector{Pair{DTask,Int}}}()

return new(arg_to_chunk, sparse_arg_wrap, arg_origin, remote_args, remote_arg_to_original, remote_arg_w, ainfo_arg, arg_history, arg_owner, arg_current, arg_overlaps, ainfo_backing_chunk,
return new(arg_to_chunk, sparse_arg_wrap, arg_origin, remote_args, remote_arg_to_original, remote_arg_w, ainfo_arg, arg_history, arg_owner, arg_current, arg_overlaps, ainfo_backing_chunk, ainfo_backing, nothing,
supports_inplace_cache, ainfo_cache, ainfos_lookup, ainfos_overlaps, ainfos_owner, ainfos_readers,
TaskArgInfo[], DataDepsTaskDependency[], Any[])
end
Expand Down Expand Up @@ -1422,6 +1526,57 @@ function add_writer!(state::DataDepsState, arg_w::ArgumentWrapper, dest_space::M
end
function add_reader!(state::DataDepsState, arg_w::ArgumentWrapper, dest_space::MemorySpace, ainfo::AbstractAliasing, task, write_num)
push!(state.ainfos_readers[ainfo], task=>write_num)
# Every task touching a slot comes through here, writers and copies
# included (`add_writer!` records them as readers too).
unkeyed = state.unkeyed_slots
unkeyed === nothing || add_unkeyed_user!(unkeyed, state, arg_w, dest_space, task)
return
end

# Attribute the `CopyKey` copy `key`, made while generating `slot`, to that slot.
function add_unkeyed_copy!(state::DataDepsState, slot, key::CopyKey)
unkeyed = state.unkeyed_slots
if unkeyed === nothing
unkeyed = state.unkeyed_slots = UnkeyedSlots()
end
idx = get(unkeyed.slot_index, slot, 0)
if idx == 0
push!(unkeyed.users, DTask[])
idx = unkeyed.slot_index[slot] = length(unkeyed.users)
end
unkeyed.copy_slot[key.id] = idx
return
end
function add_unkeyed_user!(unkeyed::UnkeyedSlots, state::DataDepsState, arg_w::ArgumentWrapper, space::MemorySpace, task::DTask)
space_args = get(state.remote_args, space, nothing)
space_args === nothing && return
slot = get(space_args, arg_w.arg, nothing)
slot === nothing && return
idx = get(unkeyed.slot_index, slot, 0)
idx == 0 && return
users = unkeyed.users[idx]
# A task reaches here once per dependency on the slot; record it once.
(isempty(users) || last(users) !== task) && push!(users, task)
return
end

"""
push_copy_users_syncdeps!(state, key::CopyKey, syncdeps)

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`).
"""
function push_copy_users_syncdeps!(state::DataDepsState, key::CopyKey, syncdeps)
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]
push!(syncdeps, ThunkSyncdep(user))
end
return
end

# Make a copy of each piece of data on each worker
Expand Down Expand Up @@ -1505,6 +1660,8 @@ function generate_slot!(state::DataDepsState, dest_space, data)
tid = something(DATADEPS_CURRENT_TASK[], (;uid=0)).uid
timing = HIER_TIMING[]
t0 = timing ? time_ns() : UInt64(0)
cache_keys = state.ainfo_backing.keys
n_keys = length(cache_keys)
data_chunk = if slot_is_already_in_place(data, orig_space, dest_space)
# 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
Expand Down Expand Up @@ -1536,6 +1693,12 @@ function generate_slot!(state::DataDepsState, dest_space, data)
end
timing && hier_log!(LogHierSlot, 0x01, LogHierSlotId(:total), time_ns() - t0)
logging && @logfinish ctx LogMove LogMoveId(0, ArgPosition(), to_proc, id) data_chunk
# Any `CopyKey` copies made just now belong to this slot alone (see
# `UnkeyedSlots`). Keys are appended in creation order on every rank.
for i in (n_keys + 1):length(cache_keys)
key = cache_keys[i]
key isa CopyKey && add_unkeyed_copy!(state, data_chunk, key)
end
@assert memory_space(data_chunk) == dest_space "space mismatch! $dest_space (dest) != $(memory_space(data_chunk)) (actual) ($(typeof(data)) (data) vs. $(typeof(data_chunk)) (chunk)), spaces ($orig_space -> $dest_space)"
dest_space_args[data] = data_chunk
state.remote_arg_to_original[data_chunk] = data
Expand Down
3 changes: 3 additions & 0 deletions src/datadeps/hierarchical.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1959,6 +1959,9 @@ function _hierarchical_copy_from_and_free!(partition_states::Vector{DataDepsStat
buf_ainfo = stored_value_ainfo(obj_cache, remote_space, ainfo)
gather_free_syncdeps!(state, remote_space, buf_ainfo, remote_arg,
write_num, chunk_to_ainfos, free_syncdeps)
# Dependency tracking orders nothing on an identity-less copy,
# so wait for every task that used its slot instead.
ainfo isa CopyKey && push_copy_users_syncdeps!(state, ainfo, free_syncdeps)
if registry !== nothing
orig = get(state.remote_arg_to_original, remote_arg, nothing)
if orig !== nothing
Expand Down
3 changes: 3 additions & 0 deletions src/datadeps/queue.jl
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,9 @@ function distribute_tasks!(queue::DataDepsTaskQueue)
free_syncdeps = Set{ThunkSyncdep}()
buf_ainfo = stored_value_ainfo(obj_cache, remote_space, ainfo)
gather_free_syncdeps!(state, remote_space, buf_ainfo, remote_arg, write_num, chunk_to_ainfos, free_syncdeps)
# Dependency tracking orders nothing on an identity-less copy, so
# 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)
end
Expand Down
Loading
Loading