From e90b472ddd86f3cb0ce6a22f365ce8e6dacc7f32 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Fri, 16 Oct 2026 19:15:21 +0200 Subject: [PATCH 1/4] Sched: sort uniform placement candidates once per candidate set, not per task Under a uniform-execution acceleration (MPI) every task re-sorted all of its candidate processors with a comparison sort whose key (processor_order_key) formats a short_name string on every comparison, and schedule_one! first built the candidate vector with a quadratic 'proc in input_procs' scan and ran estimate_task_costs!, whose result the uniform selection discards. Unscoped @spawn therefore cost O(P log P) string constructions per task and grew with the processor count: ~85 ms/task at 832 processors (see #771). * sort_processors_canonical!: compute the keys once per processor, then sortperm. * compatible_processors_ordered: cache the canonical order of a candidate set next to the compatible set (CompatEntry), so it is built once per set. * place_processors_uniform!: the per-task part only -- owner preference (binary search over the owner-sorted canonical order, three in-place reversals) and the thunk-id rotation. No scratch, no per-candidate boxing. * schedule_one!: under uniform execution start from the cached order and skip estimate_task_costs!; otherwise drop the redundant quadratic membership scan (the candidates come from a Set). * select_processors_uniform! keeps its contract (Datadeps and proc grids call it) and is now sort_processors_canonical! + place_processors_uniform!. The resulting order is identical to the old algorithm's, which uniformity across ranks depends on: test/uniform-placement.jl compares it against a copy of the old implementation on randomized candidate sets (partial scopes, absent preferred ranks, all rotations; 5770 assertions) and test/mpi/spawn.jl still passes (2 ranks x 2 threads). Measured with the new benchmark/suites/tasks.jl (suite 'tasks', ntasks=256), 4 ranks x 16 threads per node, Fulda (Opteron 6272), master vs this commit, median of 7 samples, same suite and nodes for both: unscoped spawn, 64 tasks 64 procs (1 node) 244.3 ms -> 11.7 ms (21x) 128 procs (2 nodes) 547.2 ms -> 12.2 ms (45x) 256 procs (4 nodes) 1257.9 ms -> 14.0 ms (90x) allocations of that benchmark 0.75 M -> 13 k, 1.74 M -> 19 k, 4.0 M -> 18.7 k The unscoped cost no longer grows with the processor count (about 0.2 ms/task at 256 processors). Pinned (ExactScope) benchmarks have a single candidate (the old cost estimate returned immediately for it) and are within noise; test/allocations.jl is unchanged (task spawn 183 allocs vs a bound of 500). --- src/acceleration.jl | 119 ++++++++++++++++++++++++++++---------- src/sch/Sch.jl | 96 ++++++++++++++++++++---------- test/runtests.jl | 1 + test/uniform-placement.jl | 96 ++++++++++++++++++++++++++++++ 4 files changed, 249 insertions(+), 63 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..f41661893 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,15 @@ 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. +mutable struct CompatEntry + const scope::Any + const procs::Vector{Processor} + const compat::Set{Processor} + 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 +119,51 @@ 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 + # `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 get!(()->entry, cache, key) - end - return compat + 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 = entry.ordered + if ordered === nothing + ordered = Dagger.sort_processors_canonical!(Vector{Processor}(collect(entry.compat)), accel) + entry.ordered = ordered + end + return ordered end # N.B. `mutable` (with no field ever assigned) so the 23-field struct has a @@ -1008,23 +1036,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 +1084,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) 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..07ae95339 --- /dev/null +++ b/test/uniform-placement.jl @@ -0,0 +1,96 @@ +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 From f65c8d54987714821e4d9bd74f74b786e860048b Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Fri, 16 Oct 2026 22:29:15 +0200 Subject: [PATCH 2/4] Sched: do not wake processors that cannot steal when a task is enqueued do_tasks ends every enqueue by 'kicking' the doorbell of every other processor of the scheduler, to make it try to steal. A runner whose processor may not steal (stealing_permitted false: every MPIProcessor) wakes up, finds that out and goes back to sleep, so under MPI each enqueued task woke ranks x threads runners on every rank: 256 wake-ups per task at 256 processors, about 832 at the application's size. The wake-ups are task switches on threads that could be running tasks, plus the allocations of the runner loop. Skip processors for which stealing_permitted is false. A kick only makes a runner try to steal, so skipping them cannot change which task runs where. Measured with benchmark/suites/tasks.jl on Fulda (Opteron 6272), 4 ranks x 16 threads per node, median of 7, before = 83475c6 (previous commit), 1/2/4 nodes = 4/8/16 ranks: unscoped (64 tasks) 11.0 / 12.8 / 15.9 ms -> 7.3 / 9.8 / 10.4 ms pinned, round robin (256) 44.6 / 58.9 / 47.8 ms -> 38.3 / 39.3 / 39.8 ms dependent hops (64) 55.4 / 66.2 / 64.8 ms -> 41.8 / 43.5 / 42.8 ms fan-in tree (256 leaves) 95.5 / 98.4 / 134.2 ms -> 87.9 / 90.4 / 94.0 ms allocations, pinned round robin 64.6 k / 83.1 k / 67.5 k -> 40.7 k / 41.1 k / 42.9 k allocations per pinned task in a clean loop (4 ranks x 16 threads): 183.7 -> 159.0 Every one of the 27 benchmark/size cells is faster or equal; allocations fall by 20-65 %. No semantic change: the skipped runners would not have stolen anything. --- src/sch/Sch.jl | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index f41661893..17200e32e 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -2173,6 +2173,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" From 1949e323e2c5d0d0cbe38f28f478e8e547896a54 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Sat, 17 Oct 2026 12:51:23 +0200 Subject: [PATCH 3/4] Sched: replace a stale compatible-processor cache entry instead of keeping it compat_entry inserted with BasicLFUCache.get!, which for a present key returns the existing value. After the processor list changed without a cache flush (here: a one-rank communicator's processors joining the context after the world's tasks had warmed the cache) the entry for that key no longer matched its procs, so every following lookup missed, recomputed the compatible set and re-sorted it, and the stale entry stayed. Measured on 4 ranks x 16 threads: a suite that registers the extra processors mid-run made unscoped tasks 5.3x slower with 10x the allocations (7.5 -> 40.1 ms per 64 tasks); without the registration they stay at 1.15x. Replace the entry on a miss. --- src/sch/Sch.jl | 9 ++++++++- test/uniform-placement.jl | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index 17200e32e..5d8b2ac74 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -142,7 +142,14 @@ function compat_entry(accel, scope, procs::Vector{<:Processor}) # with `Set(gen)`. entry = CompatEntry(scope, Vector{Processor}(procs), compat, nothing) return @safe_lock_spin1 COMPAT_PROCS_CACHE cache begin - get!(()->entry, cache, key) + # 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}) = diff --git a/test/uniform-placement.jl b/test/uniform-placement.jl index 07ae95339..6bdf8b016 100644 --- a/test/uniform-placement.jl +++ b/test/uniform-placement.jl @@ -94,3 +94,25 @@ end @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 From e73de3b893210a594c3b9f6141606d37b1218cf6 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Mon, 23 Nov 2026 21:45:36 +0100 Subject: [PATCH 4/4] sched: publish the canonical processor order with release/acquire compatible_processors_ordered fills CompatEntry.ordered without holding the cache lock. Two threads that race on a fresh entry may both sort the set, which is harmless because the result is deterministic, but a plain store of the vector pointer does not order the vector's contents before the pointer for a reader on another thread (weak memory models such as ARM), so it is a data race. Make the field atomic: read it with acquire, publish with release. Duplicate sorting is still allowed; no lock is added to the placement path. Test: threads that start together on a freshly invalidated entry must all see the complete canonical vector. It passes on the old code too on this machine (the race is a memory-ordering one); it guards the behaviour, not the ordering. --- src/sch/Sch.jl | 12 ++++++++---- test/uniform-placement.jl | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index 5d8b2ac74..50ae6cbae 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -99,12 +99,14 @@ completion handler (via `schedule_dependents!`) so there is no central ready que # guards against objectid reuse after GC and keeps the scope alive so its id # cannot be recycled while the entry lives. # One cached (accel, scope, procs) lookup. `ordered` is the same set in the -# acceleration's canonical order, built on first use by uniform placement. +# 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} - ordered::Union{Nothing,Vector{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 @@ -165,10 +167,12 @@ vector is shared: callers must not mutate it. """ function compatible_processors_ordered(accel, scope, procs::Vector{<:Processor}) entry = compat_entry(accel, scope, procs) - ordered = entry.ordered + 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) - entry.ordered = ordered + @atomic :release entry.ordered = ordered end return ordered end diff --git a/test/uniform-placement.jl b/test/uniform-placement.jl index 6bdf8b016..347a5fbea 100644 --- a/test/uniform-placement.jl +++ b/test/uniform-placement.jl @@ -116,3 +116,23 @@ Dagger.compatible_processors(::UniformPlacementAccel, ::Dagger.AbstractScope, pr @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