diff --git a/src/acceleration.jl b/src/acceleration.jl index 409bd2c5a..e4eea0973 100644 --- a/src/acceleration.jl +++ b/src/acceleration.jl @@ -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)) @@ -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) @@ -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 diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index 2700fbb6d..50ae6cbae 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -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 @@ -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 @@ -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 + 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 @@ -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. @@ -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) @@ -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" diff --git a/test/runtests.jl b/test/runtests.jl index 4d1a1fea4..35aa76788 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -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"), diff --git a/test/uniform-placement.jl b/test/uniform-placement.jl new file mode 100644 index 000000000..347a5fbea --- /dev/null +++ b/test/uniform-placement.jl @@ -0,0 +1,138 @@ +using Dagger, Random, Test + +# A rank-uniform acceleration with synthetic processors, so the uniform +# placement helpers can be checked without MPI. +struct UniformPlacementAccel <: Dagger.Acceleration end +struct RankProc <: Dagger.Processor + rank::Int + tid::Int +end +Dagger.uniform_execution(::UniformPlacementAccel) = true +Dagger.fire_order_key(p::RankProc) = (p.rank, p.rank) +Dagger.short_name(p::RankProc) = "(rank $(p.rank), thread $(p.tid))" +# The "state" argument carries the preferred rank in these tests +Dagger.task_processor_preference(::UniformPlacementAccel, ::Dagger.Thunk, pref) = pref + +# The original implementation: a comparison sort whose key (with its +# `short_name` string) is rebuilt per comparison, then the same rotation. +function reference_select_uniform!(procs, accel, task, pref) + sort!(procs, by=p -> ( + pref !== nothing && Dagger.processor_owner_rank(accel, p) != pref, + Dagger.processor_order_key(accel, p)..., + )) + n = length(procs) + if pref !== nothing + n = 0 + for proc in procs + Dagger.processor_owner_rank(accel, proc) == pref || break + n += 1 + end + n == 0 && (n = length(procs)) + end + if n > 1 + offset = mod(task.id - 1, n) + reverse!(procs, 1, offset) + reverse!(procs, offset + 1, n) + reverse!(procs, 1, n) + end + return procs +end + +@testset "Uniform placement" begin + accel = UniformPlacementAccel() + rng = MersenneTwister(1) + noop() = nothing + + @testset "canonical order groups processors by owner rank" begin + procs = Dagger.Processor[RankProc(r, t) for r in 3:-1:0 for t in 1:3] + shuffle!(rng, procs) + @test Dagger.sort_processors_canonical!(procs, accel) === procs + @test [p.rank for p in procs] == sort([p.rank for p in procs]) + @test issorted(procs; by=p -> Dagger.processor_order_key(accel, p)) + end + + @testset "matches the reference algorithm" begin + for nranks in (1, 2, 5), nthreads in (1, 3, 8), trial in 1:20 + candidates = Dagger.Processor[RankProc(r, t) for r in 0:nranks-1 for t in 1:nthreads] + # A scope may admit only some processors of a rank, or skip a rank + keep = rand(rng, length(candidates)) .< 0.8 + any(keep) || (keep[1] = true) + candidates = candidates[keep] + # Includes a rank that owns none of the candidates + for pref in (nothing, 0, nranks - 1, nranks + 7), tid in (1, 2, 17, 1000) + task = Dagger.Thunk(noop; id=tid) + want = reference_select_uniform!(shuffle(rng, candidates), accel, task, pref) + # Per-task path from a cached canonical order + canonical = Dagger.sort_processors_canonical!(shuffle(rng, candidates), accel) + got = Dagger.place_processors_uniform!(copy(canonical), accel, task, pref) + @test got == want + # The one-shot entry point agrees as well + got2 = Dagger.select_processors_uniform!(shuffle(rng, candidates), accel, task, pref) + @test got2 == want + end + end + end + + @testset "no task keeps the canonical order" begin + procs = Dagger.Processor[RankProc(r, t) for r in 0:2 for t in 1:2] + shuffled = shuffle(rng, procs) + @test Dagger.select_processors_uniform!(shuffled, accel) == procs + @test Dagger.place_processors_uniform!(copy(procs), accel, nothing, nothing) == procs + end + + @testset "empty and single candidate" begin + task = Dagger.Thunk(noop; id=5) + for pref in (nothing, 0) + @test Dagger.place_processors_uniform!(Dagger.Processor[], accel, task, pref) == Dagger.Processor[] + @test Dagger.place_processors_uniform!(Dagger.Processor[RankProc(0, 1)], accel, task, pref) == Dagger.Processor[RankProc(0, 1)] + end + end + + @testset "non-uniform accelerations are untouched" begin + procs = Dagger.Processor[RankProc(2, 1), RankProc(0, 1)] + want = copy(procs) + @test Dagger.select_processors_uniform!(procs, Dagger.DistributedAcceleration(), Dagger.Thunk(noop; id=3), nothing) == want + end +end + +# A cached (accel, scope, procs) lookup whose processor list changed without a cache +# flush must be replaced, not served stale: `BasicLFUCache.get!` keeps the old entry for +# a present key, which made every later lookup miss and recompute (and re-sort) the set. +Dagger.compatible_processors(::UniformPlacementAccel, ::Dagger.AbstractScope, procs::Vector{<:Dagger.Processor}) = + Set{Dagger.Processor}(procs) +@testset "compat cache replaces a stale entry" begin + accel = UniformPlacementAccel() + scope = Dagger.AnyScope() + Dagger.Sch.invalidate_compat_procs_cache!() + procs = Dagger.Processor[RankProc(r, 1) for r in 0:1] + e1 = Dagger.Sch.compat_entry(accel, scope, procs) + @test e1.compat == Set(procs) + @test Dagger.Sch.compat_entry(accel, scope, procs) === e1 + grown = Dagger.Processor[RankProc(r, 1) for r in 0:2] + e2 = Dagger.Sch.compat_entry(accel, scope, grown) + @test e2.compat == Set(grown) + # The new entry is what the cache now holds: the next lookup hits + @test Dagger.Sch.compat_entry(accel, scope, grown) === e2 + @test Dagger.Sch.compatible_processors_ordered(accel, scope, grown) == grown + Dagger.Sch.invalidate_compat_procs_cache!() +end + +# `ordered` is filled without the cache lock: threads that race on a fresh entry may each sort the +# set, and every one of them must see a complete, canonical vector (never a partial or stale one). +@testset "compatible_processors_ordered is safe to race on a fresh entry" begin + accel = UniformPlacementAccel() + scope = Dagger.AnyScope() + procs = Dagger.Processor[RankProc(r, 1) for r in 3:-1:0] + want = Dagger.Processor[RankProc(r, 1) for r in 0:3] + for _ in 1:200 + Dagger.Sch.invalidate_compat_procs_cache!() + go = Threads.Atomic{Bool}(false) + tasks = [Threads.@spawn begin + while !go[]; end + Dagger.Sch.compatible_processors_ordered(accel, scope, procs) + end for _ in 1:max(2, Threads.nthreads())] + go[] = true + @test all(==(want), fetch.(tasks)) + end + Dagger.Sch.invalidate_compat_procs_cache!() +end