Skip to content
Closed
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
119 changes: 88 additions & 31 deletions src/acceleration.jl
Original file line number Diff line number Diff line change
Expand Up @@ -179,18 +179,6 @@ bind_moved_argument(::Acceleration, original, moved) = moved
"Logical execution rank of `proc` used for uniform task placement preference."
processor_owner_rank(accel::Acceleration, proc::Processor) = first(fire_order_key(proc))

# This scan dispatches on abstract Processor elements. Pass the acceleration
# through unspecialized so an isbits backend is not boxed for every candidate;
# keep the barrier out of line so inlining does not reintroduce those boxes.
@noinline function preferred_processor_count(procs, @nospecialize(accel), rank)
n = 0
for proc in procs
processor_owner_rank(accel, proc) == rank || break
n += 1
end
return n
end

"Deterministic ordering key for `proc` under uniform execution."
processor_order_key(accel::Acceleration, proc::Processor) =
(fire_order_key(proc)..., short_name(proc))
Expand All @@ -211,30 +199,76 @@ partition_affinity_id(proc::Processor) = partition_affinity_id(only(memory_space
task_processor_preference(accel::Acceleration, task, state) = nothing

"""
select_processors_uniform!(procs, accel, task=nothing, state=nothing)
sort_processors_canonical!(procs, accel)

Sort `procs` into the canonical order of `accel`: ascending
[`processor_order_key`](@ref), which begins with the processor's owner rank
(`processor_owner_rank`) and so groups each rank's processors contiguously.
The keys are computed once per processor: a comparison sort that rebuilds them
per comparison (each one formats a `short_name` string) costs `O(n log n)`
string constructions.
"""
function sort_processors_canonical!(procs, accel::Acceleration)
length(procs) <= 1 && return procs
keys = map(p -> processor_order_key(accel, p), procs)
return permute!(procs, sortperm(keys))
end

# Index range of the processors owned by `rank` in canonically sorted `procs`
# (empty, `lo > hi`, when it owns none). Binary search: the canonical order is
# sorted by owner rank. The acceleration is passed through unspecialized, and
# the barrier kept out of line, so an isbits backend is boxed once per search
# instead of once per probed (abstractly typed) processor.
@noinline function preferred_processor_range(procs, @nospecialize(accel), rank)
n = length(procs)
lo, hi = 1, n + 1
while lo < hi
mid = (lo + hi) >>> 1
if processor_owner_rank(accel, @inbounds procs[mid]) < rank
lo = mid + 1
else
hi = mid
end
end
first_idx = lo
hi = n + 1
while lo < hi
mid = (lo + hi) >>> 1
if processor_owner_rank(accel, @inbounds procs[mid]) <= rank
lo = mid + 1
else
hi = mid
end
end
return first_idx, lo - 1
end

Re-sort `procs` with a deterministic, acceleration-dispatched key when
`uniform_execution(accel)` so every rank gets the same order (and with a
`task` the acceleration may prefer the rank owning task argument data).
Rotate the candidates within that preferred rank (or all candidates when
there is no eligible preferred rank) using the task ID, so independent tasks
spread across processors without consulting rank-local load or ready order.
Calls without a task retain the canonical order used by Datadeps and proc grids.
When not under uniform execution, leaves `procs` unchanged.
"""
function select_processors_uniform!(procs, accel::Acceleration,
task=nothing, state=nothing)
uniform_execution(accel) || return procs
pref = task_processor_preference(accel, task, state)
sort!(procs, by=p -> (
pref !== nothing && processor_owner_rank(accel, p) != pref,
processor_order_key(accel, p)...,
))
place_processors_uniform!(procs, accel, task, state)

Given `procs` already in canonical order (see [`sort_processors_canonical!`](@ref)),
apply the per-task part of uniform placement: with a `task`, move the processors
of the rank the acceleration prefers for it (the owner of its argument data) to
the front, then rotate the candidates of that rank (or all of them when there is
no eligible preferred rank) by the task ID, so independent tasks spread across
processors without consulting rank-local load or ready order. Everything is an
in-place reversal: no scratch and no per-candidate allocation.
"""
function place_processors_uniform!(procs, accel::Acceleration, task, state)
task === nothing && return procs
n = length(procs)
pref = task_processor_preference(accel, task, state)
if pref !== nothing
n = preferred_processor_count(procs, accel, pref)
n == 0 && (n = length(procs))
lo, hi = preferred_processor_range(procs, accel, pref)
if lo <= hi
if lo > 1
# `[others][preferred]` -> `[preferred][others]`, both parts keep their order
reverse!(procs, 1, hi)
reverse!(procs, 1, hi - lo + 1)
reverse!(procs, hi - lo + 2, hi)
end
n = hi - lo + 1
end
end
if n > 1
offset = mod(task.id - 1, n)
Expand All @@ -246,6 +280,29 @@ function select_processors_uniform!(procs, accel::Acceleration,
return procs
end

"""
select_processors_uniform!(procs, accel, task=nothing, state=nothing)

Re-sort `procs` with a deterministic, acceleration-dispatched key when
`uniform_execution(accel)` so every rank gets the same order (and with a
`task` the acceleration may prefer the rank owning task argument data).
Rotate the candidates within that preferred rank (or all candidates when
there is no eligible preferred rank) using the task ID, so independent tasks
spread across processors without consulting rank-local load or ready order.
Calls without a task retain the canonical order used by Datadeps and proc grids.
When not under uniform execution, leaves `procs` unchanged.

Callers that place many tasks over the same candidate set should keep the
canonical order (`sort_processors_canonical!`) and call
[`place_processors_uniform!`](@ref) per task instead.
"""
function select_processors_uniform!(procs, accel::Acceleration,
task=nothing, state=nothing)
uniform_execution(accel) || return procs
sort_processors_canonical!(procs, accel)
return place_processors_uniform!(procs, accel, task, state)
end

# Default processor grid for block assignment of new distributed arrays.
# Returns `nothing` to let the scheduler choose freely; uniform-execution
# accelerations (MPI) override this to produce a deterministic assignment
Expand Down
114 changes: 81 additions & 33 deletions src/sch/Sch.jl
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import ..Dagger: Context, Processor, SchedulerOptions, Options, Thunk, WeakThunk
import ..Dagger: Sealed, SEALED, FutureNode, futures_push!, futures_seal!
import ..Dagger: DepNode, deps_push!, deps_seal!
import ..Dagger: order, dependents, noffspring, istask, inputs, unwrap_weak, unwrap_weak_checked, wrap_weak, tochunk, timespan_start, timespan_finish, procs, move, chunktype, default_enabled, processor, get_processors, get_parent, execute!, rmprocs!, task_processor, constrain, cputhreadtime, maybe_take_or_alloc!
import ..Dagger: datasize, root_worker_id, is_local_processor, fire_order_key, short_name, select_processors_uniform!, processor_order_key, current_acceleration, set_task_acceleration!, scheduling_ignore_capacity, scheduling_task_occupancy, schedule_argument_move, argument_move_may_inline, sched_move, bind_moved_argument
import ..Dagger: datasize, root_worker_id, is_local_processor, fire_order_key, short_name, select_processors_uniform!, processor_order_key, uniform_execution, current_acceleration, set_task_acceleration!, scheduling_ignore_capacity, scheduling_task_occupancy, schedule_argument_move, argument_move_may_inline, sched_move, bind_moved_argument
import ..Dagger: @dagdebug, @safe_lock_spin1, @maybelog, @take_or_alloc!
import ..Dagger: LogCompute, LogComputeId, LogMove, LogMoveId, LogTake, LogTakeId
import ..Dagger: LogProcRunWait, LogProcRunWaitId, LogProcRunFetch, LogProcRunFetchId
Expand Down Expand Up @@ -98,7 +98,17 @@ completion handler (via `schedule_dependents!`) so there is no central ready que
# The entry retains the scope object itself: hits require `===`, which both
# guards against objectid reuse after GC and keeps the scope alive so its id
# cannot be recycled while the entry lives.
const COMPAT_PROCS_CACHE = LockedObject(Dagger.BasicLFUCache{Tuple{UInt,UInt},Tuple{Any,Vector{Processor},Set{Processor}}}(256))
# One cached (accel, scope, procs) lookup. `ordered` is the same set in the
# acceleration's canonical order, built on first use by uniform placement. It is
# filled without the cache lock, so it is atomic: the release store publishes the
# fully built vector to a thread that reads it with an acquire load.
mutable struct CompatEntry
const scope::Any
const procs::Vector{Processor}
const compat::Set{Processor}
@atomic ordered::Union{Nothing,Vector{Processor}}
end
const COMPAT_PROCS_CACHE = LockedObject(Dagger.BasicLFUCache{Tuple{UInt,UInt},CompatEntry}(256))
# Drop all cached compatible-processor sets. Called whenever the processor
# hierarchy changes (add/delete_processor_callback!) — a callback change alters
# `get_processors(::OSProc)` without changing the (accel, scope, procs) key, so
Expand All @@ -111,31 +121,60 @@ function invalidate_compat_procs_cache!()
@safe_lock_spin1 COMPAT_PROCS_CACHE cache empty!(cache)
return
end
function compatible_processors_cached(accel, scope, procs::Vector{<:Processor})
function compat_entry(accel, scope, procs::Vector{<:Processor})
key = (objectid(accel), objectid(scope))
cached = @safe_lock_spin1 COMPAT_PROCS_CACHE cache begin
entry = get(cache.cache, key, nothing)
if entry !== nothing && entry[1] === scope && entry[2] == procs
if entry !== nothing && entry.scope === scope && entry.procs == procs
cache.freq[key] += 1
entry[3]
entry
else
nothing
end
end
cached !== nothing && return cached::Set{Processor}
cached !== nothing && return cached::CompatEntry
compat = Dagger.compatible_processors(accel, scope, procs)
# N.B. `Vector{Processor}`, not `copy(procs)`: the cache's value type is
# `Tuple{Any,Vector{Processor},Set{Processor}}`, and `copy` preserves the
# caller's concrete element type (`Vector{OSProc}` from a `Context`'s procs,
# `Vector{MPIProcessor{...}}` under MPI), which fails `get!`'s typeassert.
# Only on a *miss*, so it stays hidden until some run happens not to have
# this (accel, scope) pair cached already -- see the sibling fix in generic
# `compatible_processors`, which had the same defect with `Set(gen)`.
entry = (scope, Vector{Processor}(procs), compat)
@safe_lock_spin1 COMPAT_PROCS_CACHE cache begin
get!(()->entry, cache, key)
end
return compat
# `CompatEntry`, whose `procs` field is a `Vector{Processor}`, and `copy`
# preserves the caller's concrete element type (`Vector{OSProc}` from a
# `Context`'s procs, `Vector{MPIProcessor{...}}` under MPI), which fails
# the field conversion. Only on a *miss*, so it stays hidden until some run
# happens not to have this (accel, scope) pair cached already -- see the
# sibling fix in generic `compatible_processors`, which had the same defect
# with `Set(gen)`.
entry = CompatEntry(scope, Vector{Processor}(procs), compat, nothing)
return @safe_lock_spin1 COMPAT_PROCS_CACHE cache begin
# N.B. `get!` would keep a *stale* entry for this key (one whose `procs` no longer
# matches, because the processor list changed without a cache flush) and hand it
# back, so every later call would miss again and recompute the set
if haskey(cache.cache, key)
cache.cache[key] = entry

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replacing here makes sense. One thing I noticed: the key is only (accel, scope), so if two different procs lists ever alternate on the same key, they'll keep evicting each other and re-sorting on every lookup. Before, the first one at least stayed cached. That's probably rare since procs_filt only changes when processors join, but it might be worth a line in the comment above. Specially since we'll be dealing with malleability soon this will be relevant

else
get!(()->entry, cache, key)
end
end::CompatEntry
end
compatible_processors_cached(accel, scope, procs::Vector{<:Processor}) =
compat_entry(accel, scope, procs).compat

"""
compatible_processors_ordered(accel, scope, procs) -> Vector{Processor}

The compatible processors in `accel`'s canonical order (see
`Dagger.sort_processors_canonical!`), cached with the compatible set so uniform
placement sorts a given candidate set once, not once per task. The returned
vector is shared: callers must not mutate it.
"""
function compatible_processors_ordered(accel, scope, procs::Vector{<:Processor})
entry = compat_entry(accel, scope, procs)
ordered = @atomic :acquire entry.ordered
if ordered === nothing
# Two threads may both get here and sort the same set; the result is
# deterministic, so whichever store lands last is equal to the other.
ordered = Dagger.sort_processors_canonical!(Vector{Processor}(collect(entry.compat)), accel)
@atomic :release entry.ordered = ordered
end
return ordered
end

# N.B. `mutable` (with no field ever assigned) so the 23-field struct has a
Expand Down Expand Up @@ -1008,23 +1047,27 @@ concurrently across threads.
# rank picks the same processor for this task.
accel = something(options.acceleration, current_acceleration())

input_procs = @reusable_vector :schedule_one!_input_procs Processor OSProc() 32
compat = compatible_processors_cached(accel, scope, procs_filt)
for proc in compat
if !(proc in input_procs)
push!(input_procs, proc)
end
end

sorted_procs = @reusable_vector :schedule_one!_sorted_procs Processor OSProc() 32
resize!(sorted_procs, length(input_procs))
costs = @reusable_dict :schedule_one!_costs Processor Float64 OSProc() 0.0 32
estimate_task_costs!(sorted_procs, costs, state, input_procs, task; sig)
empty!(input_procs)

# Under uniform execution, measured costs are rank-local, so re-order by a
# deterministic, acceleration-dispatched key instead (no-op otherwise).
select_processors_uniform!(sorted_procs, accel, task, state)
if uniform_execution(accel)
# Measured costs are rank-local, so under uniform execution the
# candidates are ordered by a deterministic, acceleration-dispatched key
# instead and the cost estimate would be discarded unread. Start from
# the cached canonical order of the candidate set and apply only the
# per-task part (owner preference and rotation).
ordered = compatible_processors_ordered(accel, scope, procs_filt)
resize!(sorted_procs, length(ordered))
copyto!(sorted_procs, ordered)
Dagger.place_processors_uniform!(sorted_procs, accel, task, state)
else
input_procs = @reusable_vector :schedule_one!_input_procs Processor OSProc() 32
compat = compatible_processors_cached(accel, scope, procs_filt)
# N.B. `compat` is a `Set`: its elements are already unique
append!(input_procs, compat)
resize!(sorted_procs, length(input_procs))
estimate_task_costs!(sorted_procs, costs, state, input_procs, task; sig)
empty!(input_procs)
end

# Select the best available processor and reserve time pressure optimistically.
# These operations use their own fine-grained locks — no state.lock needed.
Expand Down Expand Up @@ -1052,7 +1095,7 @@ concurrently across threads.
lock(state.running_pressure_refs) do rpr
rpr[task.id] = (counter_ref, est_time_util)
end
@dagdebug task :schedule "Scheduling to $gproc -> $proc (cost: $(costs[proc]), pressure: $(counter_ref[]))"
@dagdebug task :schedule "Scheduling to $gproc -> $proc (cost: $(get(costs, proc, 0.0)), pressure: $(counter_ref[]))"
# Uniform execution overlaps communicating tasks on a processor
# (rank-local shares); avoid serializing them into wait cycles.
est_occupancy = scheduling_task_occupancy(accel, est_occupancy)
Expand Down Expand Up @@ -2141,6 +2184,11 @@ function do_tasks(to_proc, return_queue, tasks)
if other_istate.proc === to_proc
continue
end
# A kick only makes the runner try to steal (see `start_processor_runner!`);
# one that may not steal wakes up to do nothing. Under MPI that is every
# processor of every rank, so each enqueued task would otherwise wake
# `ranks x threads` runners on every rank.
stealing_permitted(other_istate.proc) || continue
notify(other_istate.reschedule)
end
@dagdebug nothing :processor "Kicked processors"
Expand Down
1 change: 1 addition & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ tests = [
("Thunk", "thunk.jl"),
("Scheduler", "scheduler.jl"),
("Processors", "processors.jl"),
("Uniform Placement", "uniform-placement.jl"),
("Processor Grids", "procgrid.jl"),
("Memory Spaces", "memory-spaces.jl"),
("Logging", "logging.jl"),
Expand Down
Loading
Loading