From a50792ee42a665b80bde1fb0f5279aeafc5671f3 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Mon, 23 Nov 2026 21:45:36 +0100 Subject: [PATCH 1/4] Sched: cheaper placement under uniform execution (#790) * Sched: sort uniform placement candidates once per candidate set, not per task * Sched: do not wake processors that cannot steal when a task is enqueued * Sched: replace a stale compatible-processor cache entry instead of keeping it * sched: publish the canonical processor order with release/acquire --- src/acceleration.jl | 119 +++++++++++++++++++++++--------- src/sch/Sch.jl | 114 ++++++++++++++++++++++--------- test/runtests.jl | 1 + test/uniform-placement.jl | 138 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 308 insertions(+), 64 deletions(-) create mode 100644 test/uniform-placement.jl 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 From 7415afa1ee2a8c605eb6f13eef13165a4ba6afce Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Tue, 24 Nov 2026 21:16:57 +0100 Subject: [PATCH 2/4] Sched: make the cost estimate of a task with many candidate processors cheap (#791) * Sched: make the cost estimate of a task with many candidate processors cheap * sched: an empty candidate list falls through to "No processors available" again --- src/sch/Sch.jl | 6 +- src/sch/util.jl | 196 +++++++++++++++++++++++++++++++--------------- test/scheduler.jl | 7 ++ 3 files changed, 140 insertions(+), 69 deletions(-) diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index 50ae6cbae..50763132c 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -1048,7 +1048,6 @@ concurrently across threads. accel = something(options.acceleration, current_acceleration()) sorted_procs = @reusable_vector :schedule_one!_sorted_procs Processor OSProc() 32 - costs = @reusable_dict :schedule_one!_costs Processor Float64 OSProc() 0.0 32 if uniform_execution(accel) # Measured costs are rank-local, so under uniform execution the # candidates are ordered by a deterministic, acceleration-dispatched key @@ -1065,7 +1064,7 @@ concurrently across threads. # 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) + estimate_task_costs!(sorted_procs, nothing, state, input_procs, task; sig) empty!(input_procs) end @@ -1095,7 +1094,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: $(get(costs, proc, 0.0)), pressure: $(counter_ref[]))" + @dagdebug task :schedule "Scheduling to $gproc -> $proc (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) @@ -1107,7 +1106,6 @@ concurrently across threads. end end empty!(sorted_procs) - empty!(costs) # Phase 3 โ€” brief state.lock hold: fire or fail the task. # `restore_ready` only becomes non-empty if a task completes synchronously diff --git a/src/sch/util.jl b/src/sch/util.jl index 3334c2011..58804e56f 100644 --- a/src/sch/util.jl +++ b/src/sch/util.jl @@ -708,14 +708,106 @@ function estimate_task_costs(state, procs, task; sig=nothing) end const DEFAULT_TRANSFER_RATE = UInt64(1_000_000) const EMPTY_TRANSFER_RATES = Dict{Processor,UInt64}() + +# The candidates are a `Vector{Processor}`, so every call on an element (`get_parent`, +# `root_worker_id`, a lookup keyed by it) is a dynamic dispatch; at 1-2 us apiece on a +# slow core that was most of the per-candidate cost. Nearly always all candidates have +# one concrete type (every thread of a process): pass it as a function barrier, so the +# loops below are compiled for it. Mixed candidates use `Processor` and stay dynamic. +function candidate_type(procs) + P = typeof(@inbounds procs[1]) + for idx in 2:length(procs) + typeof(@inbounds procs[idx]) === P || return Processor + end + return P +end + +function fill_pressures!(pressures, procs, wtp, ::Type{P}) where {P} + last_pid = -1 + local proc_map + for idx in eachindex(procs) + proc = (@inbounds procs[idx])::P + pid = Dagger.root_worker_id(get_parent(proc)) + if pid != last_pid + proc_map = get(wtp, pid, nothing) + last_pid = pid + end + if proc_map === nothing + @inbounds pressures[idx] = UInt64(0) + continue + end + counter_ref = get(proc_map, proc, nothing) + @inbounds pressures[idx] = counter_ref === nothing ? UInt64(0) : counter_ref[] + end + return +end + +# Returns whether every candidate costs the same +function fill_costs!(cost_vec, procs, wtr, pressures, tx_costs, est_time_util, have_chunks, ::Type{P}) where {P} + first_cost = 0.0 + all_equal = true + last_pid = -1 + rates = EMPTY_TRANSFER_RATES + for idx in eachindex(procs) + proc = (@inbounds procs[idx])::P + gproc = get_parent(proc) + pid = Dagger.root_worker_id(gproc) + if pid != last_pid + rates = get(wtr, pid, EMPTY_TRANSFER_RATES) + last_pid = pid + end + + # Add fixed cost for cross-worker task transfer (esimated at 1ms) + # TODO: Actually estimate/benchmark this + task_xfer_cost = pid != myid() ? 1_000_000 : 0 # 1ms + + # N.B. `tx_rate` is in bytes per *second* (see the `transfer_rate` + # metadata `do_task` reports, which divides by a nanosecond + # duration scaled by 10^9), so `bytes/tx_rate` comes out in + # seconds while every other term here is in nanoseconds. Scale it + # up, or transfer cost is discounted by a factor of a billion and + # data locality never affects the choice of processor. + tx_cost = if have_chunks + tx_rate = get(rates, proc, DEFAULT_TRANSFER_RATE) + (tx_costs[gproc]/tx_rate) * 1e9 + else + 0.0 + end + cost = est_time_util + @inbounds(pressures[idx]) + tx_cost + task_xfer_cost + @inbounds cost_vec[idx] = cost + if idx == 1 + first_cost = cost + elseif cost != first_cost + all_equal = false + end + end + return all_equal +end + +""" + estimate_task_costs!(sorted_procs, costs, state, procs, task; sig=nothing) + +Fill `sorted_procs` with `procs` ordered by estimated cost of running `task` (cheapest +first; equally costly processors in random order). `costs` is an optional +`Dict{Processor,Float64}` that receives the estimate of each processor; the scheduler +passes `nothing`, because a dictionary keyed by an abstractly typed, isbits processor +allocates a box for every insertion and is looked up again by the sort. + +N.B. Everything is kept in vectors aligned with `procs`, and what is the same for every +candidate is computed once: this runs for every task with several candidate processors +(any unscoped task on a multi-threaded process), where the dictionaries and per- +candidate lookups cost about 130 us for 16 threads and grew with the thread count. +""" @reuse_scope function estimate_task_costs!(sorted_procs, costs, state, procs, task; sig=nothing) - if length(procs) == 1 + np = length(procs) + np == 0 && return # nothing to rank: the caller reports "No processors available" + if np == 1 # Nothing to rank: the costs only exist to order the candidates, and a # scan of the task's chunks to order one of them is pure overhead. This # is the common shape for Datadeps, which pins every task to one space. proc = procs[1] sorted_procs[1] = proc - costs[proc] = 0.0 + costs === nothing || (costs[proc] = 0.0) return end @@ -726,6 +818,7 @@ const EMPTY_TRANSFER_RATES = Dict{Processor,UInt64}() push!(chunks, Dagger.value(input)::Chunk) end end + have_chunks = !isempty(chunks) # Estimate the cost of executing the task itself if sig === nothing @@ -736,16 +829,19 @@ const EMPTY_TRANSFER_RATES = Dict{Processor,UInt64}() # Estimate network transfer cost per *parent* processor. Chunks are located # per worker, so this depends only on `get_parent(proc)`, and `procs` is # commonly every thread of a single worker -- computing it per processor - # would redo identical work (a scan of every chunk) once per thread. + # would redo identical work (a scan of every chunk) once per thread. With no + # Chunk argument there is nothing to transfer and the table stays empty. # N.B. We treat same-worker transfers as having zero transfer cost # TODO: For non-Chunk, model cost from scheduler to worker # TODO: Measure and model processor move overhead tx_costs = @reusable_dict :estimate_task_costs_tx_costs Processor Float64 OSProc() 0.0 8 - for proc in procs - gproc = get_parent(proc) - haskey(tx_costs, gproc) && continue - chunks_filt = Iterators.filter(c->get_parent(processor(c)) != gproc, chunks) - tx_costs[gproc] = impute_sum(datasize(chunk) for chunk in chunks_filt) + if have_chunks + for proc in procs + gproc = get_parent(proc) + haskey(tx_costs, gproc) && continue + chunks_filt = Iterators.filter(c->get_parent(processor(c)) != gproc, chunks) + tx_costs[gproc] = impute_sum(datasize(chunk) for chunk in chunks_filt) + end end empty!(chunks) @@ -756,78 +852,48 @@ const EMPTY_TRANSFER_RATES = Dict{Processor,UInt64}() # added to every candidate is a constant offset that cancels out of the # comparison, leaving the scheduler blind to which processors are idle. # Gathered in its own pass so `worker_time_pressure` is locked once, and - # not nested inside the `worker_transfer_rate` hold below. + # not nested inside the `worker_transfer_rate` hold below. The per-worker + # table is looked up once per run of candidates of the same worker. pressures = @reusable_vector :estimate_task_costs_pressures UInt64 UInt64(0) 32 - resize!(pressures, length(procs)) + resize!(pressures, np) + P = candidate_type(procs) lock(state.worker_time_pressure) do wtp - for (idx, proc) in enumerate(procs) - pid = Dagger.root_worker_id(get_parent(proc)) - proc_map = get(wtp, pid, nothing) - if proc_map === nothing - pressures[idx] = UInt64(0) - continue - end - counter_ref = get(proc_map, proc, nothing) - pressures[idx] = counter_ref === nothing ? UInt64(0) : counter_ref[] - end + fill_pressures!(pressures, procs, wtp, P) end # Estimate total cost for executing this task on each candidate processor. # The transfer-rate table is taken once rather than once per processor. # N.B. `all_equal` is returned from the locked block rather than assigned # to a captured outer local, which would Core.Box it. + cost_vec = @reusable_vector :estimate_task_costs_costs Float64 0.0 32 + resize!(cost_vec, np) all_equal = lock(state.worker_transfer_rate) do wtr - local first_cost = 0.0 - local all_equal = true - for (idx, proc) in enumerate(procs) - gproc = get_parent(proc) - pid = Dagger.root_worker_id(gproc) - - # Add fixed cost for cross-worker task transfer (esimated at 1ms) - # TODO: Actually estimate/benchmark this - task_xfer_cost = pid != myid() ? 1_000_000 : 0 # 1ms - - # N.B. `tx_rate` is in bytes per *second* (see the `transfer_rate` - # metadata `do_task` reports, which divides by a nanosecond - # duration scaled by 10^9), so `bytes/tx_rate` comes out in - # seconds while every other term here is in nanoseconds. Scale it - # up, or transfer cost is discounted by a factor of a billion and - # data locality never affects the choice of processor. - tx_rate = get(get(wtr, pid, EMPTY_TRANSFER_RATES), proc, DEFAULT_TRANSFER_RATE) - tx_cost = (tx_costs[gproc]/tx_rate) * 1e9 - cost = est_time_util + pressures[idx] + tx_cost + task_xfer_cost - costs[proc] = cost - if idx == 1 - first_cost = cost - elseif cost != first_cost - all_equal = false - end - end - return all_equal + fill_costs!(cost_vec, procs, wtr, pressures, tx_costs, est_time_util, have_chunks, P) end empty!(tx_costs) empty!(pressures) - # Shuffle procs around, so equally-costly procs are equally considered - np = length(procs) - if np == 1 - # Nothing to shuffle - sorted_procs[1] = procs[1] - else - @reusable :estimate_task_costs_P Vector{Int} 0 4 np P begin - resize!(P, np) - copyto!(P, 1:np) - randperm!(P) - for idx in 1:np - sorted_procs[idx] = procs[P[idx]] - end + # Shuffle procs around, so equally-costly procs are equally considered, then + # sort the shuffled indices by lowest cost first (stable, so ties keep their + # random order). The sort is skipped when every processor costs the same (the + # usual single-worker case), where the shuffle already gives the arbitrary- + # but-fair order that sorting would leave us with anyway. + @reusable :estimate_task_costs_P Vector{Int} 0 4 np P begin + resize!(P, np) + copyto!(P, 1:np) + randperm!(P) + all_equal || sort!(P, by=i->@inbounds(cost_vec[i])) + for idx in 1:np + @inbounds sorted_procs[idx] = procs[P[idx]] end end - - # Sort by lowest cost first. Skipped when every processor costs the same - # (the usual single-worker case), where the shuffle above already gives the - # arbitrary-but-fair order that sorting would leave us with anyway. - all_equal || sort!(sorted_procs, by=p->costs[p]) + if costs !== nothing + for idx in 1:np + costs[procs[idx]] = cost_vec[idx] + end + end + empty!(cost_vec) + return end """ diff --git a/test/scheduler.jl b/test/scheduler.jl index aaad28cf7..23292605d 100644 --- a/test/scheduler.jl +++ b/test/scheduler.jl @@ -862,3 +862,10 @@ end @test length(unique(ids)) > 1 end end + +@testset "No candidate processors gives a SchedulingException" begin + # A scope that matches no processor leaves `estimate_task_costs!` with an empty candidate list; the + # task must fail with the usual "No processors available" message, not with an UndefRefError. + nowhere = Dagger.ExactScope(Dagger.ThreadProc(1, typemax(Int) - 1)) + @test_throws_unwrap (Dagger.DTaskFailedException, Dagger.Sch.SchedulingException) reason="No processors available, try widening scope" fetch(Dagger.@spawn scope=nowhere identity(1)) +end From bcfe2d62f6834202fef2d7f14d31da088439bb55 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Fri, 20 Nov 2026 12:04:18 -0600 Subject: [PATCH 3/4] datadeps: NoAliasing arguments no longer share one slot (#792) * datadeps: NoAliasing arguments no longer share one slot --- src/datadeps/aliasing.jl | 4 ++++ test/mpi/cpu.jl | 1 + test/mpi/noaliasing_args.jl | 23 +++++++++++++++++++++++ 3 files changed, 28 insertions(+) create mode 100644 test/mpi/noaliasing_args.jl diff --git a/src/datadeps/aliasing.jl b/src/datadeps/aliasing.jl index f8de25146..cfce21de5 100644 --- a/src/datadeps/aliasing.jl +++ b/src/datadeps/aliasing.jl @@ -635,6 +635,10 @@ 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 x_space = memory_space(x) if !is_key_present(cache, x_space, ainfo) # Preserve the object's memory-space/processor pairing when inserting diff --git a/test/mpi/cpu.jl b/test/mpi/cpu.jl index 82b2a4501..ba97dfd08 100644 --- a/test/mpi/cpu.jl +++ b/test/mpi/cpu.jl @@ -146,6 +146,7 @@ end end include("spawn.jl") +include("noaliasing_args.jl") @testset "Datadeps" begin diff --git a/test/mpi/noaliasing_args.jl b/test/mpi/noaliasing_args.jl new file mode 100644 index 000000000..df7077903 --- /dev/null +++ b/test/mpi/noaliasing_args.jl @@ -0,0 +1,23 @@ +# 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) + +@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) + 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 From 687589ed3154b8da4d753d053543fce27f92cf4c Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Tue, 24 Nov 2026 20:59:58 +0100 Subject: [PATCH 4/4] MPI: drop a plain task's ref-id counter when the task is done (#793) * MPI: drop a plain task's ref-id counter when the task is done * MPI: review fixes for the ref-id cleanup (no in_task check, exact table size in the test) --- ext/MPIExt.jl | 19 +++++++++++++++++++ test/mpi/spawn.jl | 23 +++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index 502c52448..0d2d640ab 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -2429,7 +2429,26 @@ function mpi_execute_bcast_plan(f, args, proc::MPIProcessor) return (; need_type_bcast=false, nothrow, inferred) end +# A task that is not part of a Datadeps region (no tag option) generates ref ids only while it +# is moved to and executed on its processor, never during planning, so once `execute!` returns +# nobody takes another id for its thunk id and its sub-counter is dead. Without this the table +# grew by one entry per task until the next Datadeps `wait_all`, which a program that only uses +# `@spawn` never reaches. Datadeps tasks (tagged) keep the later cleanup: their planning shares +# the key with their execution, and reclaiming between the two would collide on sub-ids. function execute!(proc::MPIProcessor, f, args...; kwargs...) + opts = Dagger.get_tls().task_spec.options + if opts !== nothing && opts.tag === nothing + tid = sch_handle().thunk_id.id + try + return mpi_execute_body(proc, f, args...; kwargs...) + finally + mpi_cleanup_tid(tid) + end + end + return mpi_execute_body(proc, f, args...; kwargs...) +end + +function mpi_execute_body(proc::MPIProcessor, f, args...; kwargs...) local_rank = MPI.Comm_rank(proc.comm) islocal = local_rank == proc.rank inplace_move = f === move! diff --git a/test/mpi/spawn.jl b/test/mpi/spawn.jl index fc74028bc..5a87f385f 100644 --- a/test/mpi/spawn.jl +++ b/test/mpi/spawn.jl @@ -2,6 +2,8 @@ # progress at different speeds. Check actual execution, scopes, and locality. mpi_spawn_location(x=nothing) = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid(), x) mpi_spawn_value() = (sleep(0.05); 42) +mpi_spawn_value_fast(i) = 42 + i - i +mpi_spawn_checked(i::Int) = i > 0 ? i : error("negative") function check_spawn_placements(tasks, allowed, value=nothing) placements = Dagger.Processor[] @@ -84,3 +86,24 @@ end end end end + +# The ref-id bookkeeping of a task that is not part of a Datadeps region is dropped when the +# task is done; it used to grow by one entry per task for the whole session +reftid_size() = lock(d -> length(d), MPIExt._MPIREF_TID) +@testset "Ref-id table does not grow with plain tasks" begin + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) + foreach(fetch, [Dagger.@spawn(mpi_spawn_value_fast(i)) for i in 1:8]) # warm up + MPI.Barrier(comm) + before = reftid_size() + # unscoped, pinned to every rank in turn, and a body that may throw + foreach(wait, [Dagger.@spawn(mpi_spawn_value_fast(i)) for i in 1:100]) + foreach(wait, [Dagger.@spawn(scope=Dagger.ExactScope(cpus[mod1(i, length(cpus))]), mpi_spawn_value_fast(i)) for i in 1:100]) + foreach(wait, [Dagger.@spawn(mpi_spawn_checked(i)) for i in 1:100]) + MPI.Barrier(comm) + # Nothing is left behind by 300 tasks + @test reftid_size() == before + # and ids are still uniform afterwards + t = Dagger.@spawn mpi_spawn_value_fast(1) + @test fetch(t) == 42 + @test allequal(MPI.Allgather(Int(t.uid), comm)) +end