diff --git a/docs/src/scheduler-internals.md b/docs/src/scheduler-internals.md index 52108a1ff..61c26b2d5 100644 --- a/docs/src/scheduler-internals.md +++ b/docs/src/scheduler-internals.md @@ -81,7 +81,7 @@ Once one or more tasks are ready to be scheduled, the scheduler will begin assig - Selecting candidate processors based on the task's combined scope - Calculating the cost to move needed data to each candidate processor - Adding a "wait time" cost proportional to the estimated run time for all the tasks currently executing on each candidate processor -- Selecting the least costly candidate processor as the executor for this task +- Trying the four least costly candidates first; further candidates retain a random rotation order and need not be the next cheapest eligible processor After these operations have been performed for each task, the tasks will be fired off to their appropriate worker for handling. diff --git a/src/datadeps/queue.jl b/src/datadeps/queue.jl index 281706d66..b76744c0b 100644 --- a/src/datadeps/queue.jl +++ b/src/datadeps/queue.jl @@ -267,6 +267,22 @@ function written_positions(task_arg_ws, deps_vec) return something(writes, Int[]) end +# Every processor of a memory space gets an equal union scope (the scope does not depend on `our_proc` +# beyond its space), but `get!` builds one object per processor. The scheduler's compatible-set lookup +# then compares up to 64 member-by-member equal scopes (22 us at 64 threads on our cluster) where one shared +# object is a pointer comparison. Sharing is best-effort: bound the scan so a +# new space never searches every unrelated worker/device scope in the cache. +const SCOPE_SHARE_SCAN_LIMIT = 16 +function share_equal_scope(cache, scope) + checked = 0 + for existing in values(cache.cache) + checked >= SCOPE_SHARE_SCAN_LIMIT && break + existing === scope && return existing + checked += 1 + end + return scope +end + function distribute_task!(queue::DataDepsTaskQueue, state::DataDepsState, all_procs, all_scope, spec::DTaskSpec{typed}, task::DTask, fargs, proc_to_scope_lfu, write_num::Int; ownership=nothing) where typed @specialize spec fargs @@ -310,7 +326,7 @@ function distribute_task!(queue::DataDepsTaskQueue, state::DataDepsState, all_pr # `all_procs`, both of which are fixed for this cache's lifetime. our_scope = get!(proc_to_scope_lfu, our_proc) do our_procs = filter(proc->proc in all_procs, collect(processors(our_space))) - return constrain(UnionScope(map(ExactScope, our_procs)...), DefaultScope()) + return share_equal_scope(proc_to_scope_lfu, constrain(UnionScope(map(ExactScope, our_procs)...), DefaultScope())) end else # Use the provided scope and constrain it to the available processors diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index 8fce00ca0..11692df34 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -121,8 +121,24 @@ function invalidate_compat_procs_cache!() @safe_lock_spin1 COMPAT_PROCS_CACHE cache empty!(cache) return end +# Cache key of a scope. `objectid` of a union scope hashes every member (one `ExactScope` per +# thread for the scopes Datadeps hands out), O(threads) work per task: 40 us at 64 threads. +# A large union is keyed by its length and its first and last member instead: still a function of +# the *contents*, so the equal union a later Datadeps region builds finds the entry of the earlier +# one (a key by address does not: every region would add 64 never-hit entries, and once the +# frequency-ordered cache is full the new, frequency-1 keys are evicted at once, so every task of +# the region misses). The hit test `entry.scope === scope` compares the members, and a collision +# of two different unions only replaces the entry. A small union, or any other scope, keeps `objectid`. +const SCOPE_KEY_UNION_MIN = 8 +scope_key(scope) = objectid(scope) +function scope_key(scope::Dagger.UnionScope) + scopes = scope.scopes + n = length(scopes) + n > SCOPE_KEY_UNION_MIN || return objectid(scope) + return hash(n, hash(objectid(@inbounds(scopes[1])), UInt(objectid(@inbounds(scopes[n]))))) +end function compat_entry(accel, scope, procs::Vector{<:Processor}) - key = (objectid(accel), objectid(scope)) + key = (objectid(accel), scope_key(scope)) cached = @safe_lock_spin1 COMPAT_PROCS_CACHE cache begin entry = get(cache.cache, key, nothing) if entry !== nothing && entry.scope === scope && entry.procs == procs @@ -1565,6 +1581,9 @@ end empty!(to_send) end +# Number of batches whose `do_tasks` threw (reported to the scheduler as a failure of the batch's first task). Read by tests. +const FIRE_FAILURES = Threads.Atomic{Int}(0) + struct FireTaskSpec init_proc::Processor return_chan::RemoteChannel @@ -1578,6 +1597,9 @@ function (ets::FireTaskSpec)() ctx_vars = first_task.ctx_vars::NamedTuple ctx = Dagger.log_context(ctx_vars.log_sink, ctx_vars.profile) uid = first_task.sch_uid + # Read before `do_tasks` hands the specs over: afterwards the first one may already be recycled + # (its `thunk_id` reset to 0, or reused by another task), and a failure must be reported under the id it belongs to. + first_thunk_id = first_task.thunk_id proc = ets.init_proc chan = ets.return_chan @@ -1592,10 +1614,10 @@ function (ets::FireTaskSpec)() end catch err bt = catch_backtrace() - # FIXME: Catch the correct task ID - thunk_id = first_task.thunk_id + # FIXME: Catch the correct task ID (this is the first of the batch, not necessarily the one that failed) + Threads.atomic_add!(FIRE_FAILURES, 1) if isopen(chan) - put!(chan, TaskResult(pid, proc, thunk_id, CapturedException(err, bt), nothing)) + put!(chan, TaskResult(pid, proc, first_thunk_id, CapturedException(err, bt), nothing)) end finally @logfinish ctx LogFire LogFireId(uid, pid) nothing @@ -1682,6 +1704,9 @@ mutable struct ProcessorInternalState # Free-list of reset `TaskSpec`s (with their `data` vectors and `Argument` # cells) for reuse by `fire_tasks!`. Guarded by `queue`'s lock. spec_pool::Vector{TaskSpec} + # True from the moment the runner starts looking for work until it takes a task: `do_tasks` wakes + # only runners that are parked, because one that is not will look at the queues again by itself + parked::Threads.Atomic{Bool} end struct ProcessorState state::ProcessorInternalState @@ -1809,6 +1834,10 @@ function start_processor_runner!(istate::ProcessorInternalState, uid::UInt64, re # runner creation ctx = istate.ctx + # From here until a task is taken, this runner is looking for work: a task enqueued + # from now on is seen by the dequeue/steal attempt below or wakes the doorbell + istate.parked[] = true + # Wait for new tasks if !work_to_do @dagdebug nothing :processor "Waiting for tasks" @@ -1912,6 +1941,7 @@ function start_processor_runner!(istate::ProcessorInternalState, uid::UInt64, re end @label execute + istate.parked[] = false task, task_occupancy = task_and_occupancy thunk_id = task.thunk_id time_util = task.est_time_util @@ -2140,6 +2170,16 @@ function (dts::DoTaskSpec)() return end +# Rotates where `do_tasks` starts looking for a runner to wake, so that the same runners are not always the thieves +const KICK_CURSOR = Threads.Atomic{Int}(0) +# Bound probes by a constant multiple of runners + tasks. This preserves +# selective waking for small batches even on very large thread pools. +const MAX_KICK_SCOPE_CHECKS = 8 + +# Test hook: called by `do_tasks` right after it enqueued a batch, i.e. from the moment on at which another runner may take, run and +# recycle the specs. Tests set it to a sleep to make that window wide; `nothing` (the default) costs one load and compare per batch. +const AFTER_ENQUEUE_HOOK = Ref{Any}(nothing) + """ do_tasks(to_proc, return_queue, tasks) @@ -2166,7 +2206,8 @@ function do_tasks(to_proc, return_queue, tasks) Set{Int}(), Dict{Int,Dagger.CancelToken}(), Ref(false), - TaskSpec[]) + TaskSpec[], + Threads.Atomic{Bool}(false)) start_event = Base.Event() runner = start_processor_runner!(istate, uid, return_queue, start_event) @static if VERSION < v"1.9" @@ -2186,6 +2227,14 @@ function do_tasks(to_proc, return_queue, tasks) istate.ctx = ctx end states = proc_states(uid) + # What the wake-up decision below needs is read here, while `do_tasks` still owns each spec. The + # moment a spec is in the queue another runner may take it, run it and recycle it + # (`reset_task_spec!` sets `scope` and `options` to `nothing`), so reading `tasks` again after the + # enqueue loop saw `nothing` and stale occupancies (a `TypeError` in the `scope` assertion, on + # few threads with many short tasks). + kick_scopes = @reusable_vector :do_tasks_kick_scopes Dagger.AbstractScope nothing 32 + kick_accels = @reusable_vector :do_tasks_kick_accels Dagger.Acceleration nothing 32 + kick_occupancies = @reusable_vector :do_tasks_kick_occupancies UInt32 UInt32(0) 32 lock(istate.queue) do queue for task in tasks thunk_id = task.thunk_id @@ -2218,27 +2267,74 @@ function do_tasks(to_proc, return_queue, tasks) end end should_launch || continue + if !(task.scope isa Dagger.ExactScope) + push!(kick_scopes, task.scope::Dagger.AbstractScope) + push!(kick_accels, something((task.options::Options).acceleration, Dagger.DistributedAcceleration())) + push!(kick_occupancies, occupancy) + end push!(queue, task => occupancy) @logfinish ctx LogEnqueue LogEnqueueId(uid, to_proc, thunk_id) nothing @dagdebug thunk_id :processor "Enqueued task" end end notify(istate.reschedule) + hook = AFTER_ENQUEUE_HOOK[] + hook === nothing || hook() # Kick other processors to make them steal # TODO: Alternatively, automatically balance work instead of blindly enqueueing - for other_state in states_snapshot!(STATES_CACHE_TLV[], proc_states(uid)) - other_istate = other_state.state - if other_istate.proc === to_proc - continue - end + # + # A task whose scope is an `ExactScope` can run on that one processor only (`proc_in_scope` is + # `proc == scope.processor`), so nobody can steal it and a kick would be wasted. Every kick wakes + # a runner that then scans the queues of all the others, so with T threads each enqueued task + # cost O(T) wake-ups and O(T^2) queue probes: pinned tasks went from ~8000 to ~5500 tasks/s + # between 32 and 64 threads. + isempty(kick_scopes) && return nothing + # Wake the runners that could take one of these tasks, at most one per task. Waking every + # processor made each enqueued task cost T wake-ups, each followed by a scan that locks the + # queues of all T processors: O(T^2) lock operations per task, which collapsed the throughput + # of unscoped tasks at 32 threads and more. A runner that is not parked will look at the + # queues again by itself (see `ProcessorInternalState.parked`), and one that cannot take any + # of the tasks (scope, acceleration, free occupancy) would only go back to sleep. + # If exact eligibility would exceed a linear probe budget, wake broadly and + # leave compatibility checks to stealing instead. + states_vec = states_snapshot!(STATES_CACHE_TLV[], proc_states(uid)) + nstates = length(states_vec) + nkick = 0 + maxkick = length(kick_scopes) + broad_kick = nstates > div(MAX_KICK_SCOPE_CHECKS * (nstates + maxkick), maxkick) + start_idx = nstates <= 1 ? 1 : mod1(Threads.atomic_add!(KICK_CURSOR, 1), nstates) + for state_offset in 0:(nstates-1) + state_idx = start_idx + state_offset + state_idx > nstates && (state_idx -= nstates) + other_istate = (@inbounds states_vec[state_idx]).state + other_istate.proc === to_proc && continue # 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) + other_istate.parked[] || continue + if broad_kick + notify(other_istate.reschedule) + continue + end + free = lock(other_istate.queue) do _ + typemax(UInt32) - other_istate.proc_occupancy[] + end + for idx in eachindex(kick_scopes) + scope = @inbounds kick_scopes[idx] + accel = @inbounds kick_accels[idx] + if Dagger.proc_in_scope(other_istate.proc, scope) && Dagger.accel_matches_proc(accel, other_istate.proc) && + free >= @inbounds(kick_occupancies[idx]) + notify(other_istate.reschedule) + nkick += 1 + break + end + end + nkick >= maxkick && break end + empty!(kick_scopes); empty!(kick_accels); empty!(kick_occupancies) @dagdebug nothing :processor "Kicked processors" end diff --git a/src/sch/util.jl b/src/sch/util.jl index 50a7a6d1c..61e1d36c1 100644 --- a/src/sch/util.jl +++ b/src/sch/util.jl @@ -773,11 +773,51 @@ function fill_costs!(cost_vec, procs, wtr, pressures, tx_costs, est_time_util, h return all_equal end +# How many of the cheapest candidates `order_candidates!` ranks exactly. +const PLACEMENT_SELECT = 4 + +# The scheduler tries candidates in order and nearly always takes the first, so a +# full shuffle plus a full sort (O(np log np) per task, growing with the thread +# count) is more than it needs. Rotate by a random offset (fair for equal costs) +# and select only the cheapest few into the front; the tail keeps rotation order. +# Reservoir sampling gives each tied minimum equal probability even when the +# minima are separated by different numbers of higher-cost candidates. +# N.B. A plain function: inside the `@reusable` block `best`/`bc` were captured +# and reassigned, i.e. boxed, and every comparison became a dynamic dispatch. +function order_candidates!(P::Vector{Int}, cost_vec::Vector{Float64}, all_equal::Bool) + np = length(P) + off = rand(1:np) + @inbounds for idx in 1:np + k = off + idx + P[idx] = k > np ? k - np : k + end + all_equal && return + @inbounds for j in 1:min(np - 1, PLACEMENT_SELECT) + best = j + bc = cost_vec[P[j]] + ties = 1 + for k in (j+1):np + ck = cost_vec[P[k]] + if ck < bc + best = k + bc = ck + ties = 1 + elseif ck == bc + ties += 1 + rand(1:ties) == 1 && (best = k) + end + end + P[j], P[best] = P[best], P[j] + end + return +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 +Fill `sorted_procs` with `procs`, selecting the cheapest four candidates first. +The remaining candidates retain a random rotation order, so a fallback beyond +those four need not choose the next cheapest processor. `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. @@ -871,9 +911,13 @@ candidate lookups cost about 130 us for 16 threads and grew with the thread coun # 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])) + if costs === nothing + order_candidates!(P, cost_vec, all_equal) + else + copyto!(P, 1:np) + randperm!(P) + all_equal || sort!(P, by=i->@inbounds(cost_vec[i])) + end for idx in 1:np @inbounds sorted_procs[idx] = procs[P[idx]] end diff --git a/test/scheduler.jl b/test/scheduler.jl index 4d7637f77..04ff2aad2 100644 --- a/test/scheduler.jl +++ b/test/scheduler.jl @@ -910,3 +910,91 @@ end prefix = repeat("a", 95) @test Dagger.Sch.scheduling_name(Symbol(prefix * "é")) == prefix * "…" end + +@testset "Candidate ordering" begin + order! = Dagger.Sch.order_candidates! + for np in (2, 5, 64), all_equal in (true, false) + cost = Float64.(rand(1:3, np)) + # With unequal costs a cheapest candidate must come first and the next few must be ranked; + # with equal costs (or among tied minima) every candidate must get a chance to be first. + firsts = Set{Int}() + for _ in 1:4000 + P = zeros(Int, np) + order!(P, cost, all_equal) + @test sort(P) == 1:np + if !all_equal + @test cost[P[1]] == minimum(cost) + np > 5 && @test issorted(cost[P[1:Dagger.Sch.PLACEMENT_SELECT]]) + end + push!(firsts, P[1]) + end + @test length(firsts) == (all_equal ? np : count(==(minimum(cost)), cost)) + end + # Rotation alone weights a tied minimum by the gap preceding it. These + # minima have unequal gaps, but must still receive equal first-choice weight. + cost = [0.0, 1, 0, 1, 1, 1, 1, 1] + firsts = zeros(Int, length(cost)) + P = zeros(Int, length(cost)) + for _ in 1:2000 + order!(P, cost, false) + firsts[P[1]] += 1 + end + @test 800 <= firsts[1] <= 1200 + @test 800 <= firsts[3] <= 1200 + @inferred order!(zeros(Int, 8), rand(8), false) +end + +@testset "Batch enqueue does not read a recycled spec" begin + # `do_tasks` used to read each `TaskSpec` again after enqueueing it, to decide whom to wake. A runner can run and + # recycle a short task before that (`scope` and `options` become `nothing`), which threw a TypeError in the scope + # assertion. The window is tiny on a fast machine, so the test widens it through the hook that `do_tasks` calls right + # after the enqueue; a runner on another thread then recycles the spec while `do_tasks` still sleeps. + nthr = Threads.nthreads() + tiny(i) = i + 1 + scopes = [Dagger.ExactScope(Dagger.ThreadProc(1, t)) for t in 1:nthr] + function run_many(n) + ts = DTask[] + for i in 1:n + t = i % 3 == 0 ? Dagger.@spawn(tiny(i)) : Dagger.@spawn(scope=scopes[mod1(i, nthr)], tiny(i)) + push!(ts, t) + end + return all(i -> fetch(ts[i]) == i + 1, eachindex(ts)) + end + failures0 = Dagger.Sch.FIRE_FAILURES[] + @test run_many(2000) # without the hook: smoke test + if nthr >= 2 + Dagger.Sch.AFTER_ENQUEUE_HOOK[] = () -> Libc.systemsleep(0.002) + try + @test run_many(300) + finally + Dagger.Sch.AFTER_ENQUEUE_HOOK[] = nothing + end + # The error is reported under the id of a recycled spec, so it does not always fail a task the test waits for; + # count the batches that threw instead. + @test Dagger.Sch.FIRE_FAILURES[] == failures0 + else + @test_skip run_many(300) # one thread: nothing else can run while do_tasks sleeps + end +end + +struct CountedScopeValues + data::Vector{Int} + visited::Base.RefValue{Int} +end +Base.values(values::CountedScopeValues) = values +function Base.iterate(values::CountedScopeValues, idx::Int=1) + idx > length(values.data) && return nothing + values.visited[] += 1 + return values.data[idx], idx + 1 +end +@testset "Scope sharing has a bounded search on unrelated spaces" begin + values = CountedScopeValues(collect(1:1024), Ref(0)) + cache = (; cache=values) + @test Dagger.share_equal_scope(cache, -1) == -1 + # Iteration may obtain the next element before checking the bound. + @test values.visited[] <= Dagger.SCOPE_SHARE_SCAN_LIMIT + 1 + values.data[1] = -1 + values.visited[] = 0 + @test Dagger.share_equal_scope(cache, -1) == -1 + @test values.visited[] == 1 +end