diff --git a/AGENTS.md b/AGENTS.md index ad8c5740e..2873ce446 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1217,3 +1217,12 @@ this section verbatim). Each entry is one bullet starting with `- `. the protocol alone is not enough for them. Test with a remote reader *and* a remote writer, in both orders: in one process every slot is the argument itself, so none of this is visible. + +110. **Cache invalidation must also reject in-flight publications.** Clearing + compatible-processor caches does not stop a computation that read the old + processor hierarchy from storing its answer afterwards. Carry a hierarchy + generation through computation and check it before publishing into every + cache layer; a second fast cache can otherwise restore what the first + cache correctly invalidated. Check the generation on fast hits too. A + deterministic test pauses the compatible-set computation with Events, + invalidates, then releases it and checks that the computation retries. diff --git a/docs/src/scheduler-internals.md b/docs/src/scheduler-internals.md index 52108a1ff..e9adb9ae9 100644 --- a/docs/src/scheduler-internals.md +++ b/docs/src/scheduler-internals.md @@ -81,7 +81,20 @@ 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 + +For eligible tasks whose candidate processors are all CPU threads of this +process, a short placement path compares estimated queued compute pressure. +It checks the selected processor's function and argument compatibility before +reserving pressure. With many candidates it samples two processors rather than +scanning every candidate. This local path approximates the general cost policy: +it does not rank threads by their individual measured transfer rates. Tasks +with explicit resource overrides, restricted input scopes, remote or device +candidates, or uniform execution use the general path. + +The general path also uses two-choice pressure ranking for a large candidate +set consisting entirely of CPU threads on one worker, including a remote +worker. Cross-worker and non-CPU candidates keep the transfer-aware cost path. 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..2195eea48 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -103,11 +103,15 @@ completion handler (via `schedule_dependents!`) so there is no central ready que # 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 generation::UInt const scope::Any const procs::Vector{Processor} const compat::Set{Processor} @atomic ordered::Union{Nothing,Vector{Processor}} + # The local fast path's view of this set (`missing` until first asked; see fastpath.jl) + @atomic fast::Any end +const COMPAT_PROCS_GENERATION = Threads.Atomic{UInt}(0) 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 @@ -118,41 +122,58 @@ const COMPAT_PROCS_CACHE = LockedObject(Dagger.BasicLFUCache{Tuple{UInt,UInt},Co # precompile workload (both cache-key objectids are content-stable across # sessions): `__init__`'s per-thread callback registrations trigger it. function invalidate_compat_procs_cache!() - @safe_lock_spin1 COMPAT_PROCS_CACHE cache empty!(cache) + @safe_lock_spin1 COMPAT_PROCS_CACHE cache begin + Threads.atomic_add!(COMPAT_PROCS_GENERATION, UInt(1)) + empty!(cache) + end + invalidate_fast_index!() 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)) - cached = @safe_lock_spin1 COMPAT_PROCS_CACHE cache begin - entry = get(cache.cache, key, nothing) - if entry !== nothing && entry.scope === scope && entry.procs == procs - cache.freq[key] += 1 - entry - else - nothing - end - end - 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 - # `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) + key = (objectid(accel), scope_key(scope)) + while true + generation, cached = @safe_lock_spin1 COMPAT_PROCS_CACHE cache begin + generation = COMPAT_PROCS_GENERATION[] + entry = get(cache.cache, key, nothing) + if entry !== nothing && entry.scope === scope && entry.procs == procs + cache.freq[key] += 1 + (generation, entry) + else + (generation, nothing) + end + end + cached !== nothing && return cached::CompatEntry + compat = Dagger.compatible_processors(accel, scope, procs) + entry = CompatEntry(generation, scope, Vector{Processor}(procs), compat, nothing, missing) + published = @safe_lock_spin1 COMPAT_PROCS_CACHE cache begin + # Invalidation may have run while compatible_processors computed. + # Never put its pre-invalidation answer back into either cache. + if generation != COMPAT_PROCS_GENERATION[] + nothing + elseif haskey(cache.cache, key) + cache.cache[key] = entry + else + get!(()->entry, cache, key) + end end - end::CompatEntry + published !== nothing && return published::CompatEntry + end end compatible_processors_cached(accel, scope, procs::Vector{<:Processor}) = compat_entry(accel, scope, procs).compat @@ -166,7 +187,10 @@ 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) + # The lock-free snapshot of the local fast path (see fastpath.jl) instead of the cache behind one lock: + # every placing thread of every task took that lock, 12-29 us per task at 64 threads on our cluster. + # Same entries, same canonical order; a miss falls through to `compat_entry`. + entry = fast_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 @@ -177,6 +201,8 @@ function compatible_processors_ordered(accel, scope, procs::Vector{<:Processor}) return ordered end +include("fastpath.jl") + # N.B. `mutable` (with no field ever assigned) so the 23-field struct has a # stable heap identity and is passed by pointer; as an immutable struct it was # stored inline in closures and re-boxed (~200B) on every dynamic call. @@ -1038,121 +1064,132 @@ concurrently across threads. Dagger.options_merge!(options, state.sch_options) Dagger.populate_defaults!(options, sig) - # Calculate scope. Errors are stored in `scope_ex` and applied in Phase 3. - local scope - local scope_ex = nothing - if options.exec_scope !== nothing - # Bypass scope calculation if it's been done for us already - scope = options.exec_scope - else - scope = constrain(@something(options.compute_scope, options.scope, DefaultScope()), - @something(options.result_scope, AnyScope())) - if scope isa InvalidScope - scope_ex = SchedulingException("compute_scope and result_scope are not compatible: $(scope.x), $(scope.y)") - else - for arg in task.inputs - scope_ex === nothing || break - value = unwrap_weak_checked(Dagger.value(arg)) - # After collect_task_inputs!, Thunk inputs are resolved to Chunks. - @assert !istask(value) - chunk = if value isa Chunk - value - else - nothing - end - chunk isa Chunk || continue - scope = constrain(scope, chunk.scope) - if scope isa InvalidScope - scope_ex = SchedulingException("Current scope and argument Chunk scope are not compatible: $(scope.x), $(scope.y)") - end - end - end - end - - if scope_ex !== nothing - # scope is invalid — fail the task under state.lock (set_failed! requires it) - lock(state.lock) do - set_failed!(state, task; ex=scope_ex) - # Release the `running_count` credit `task` received when it - # entered `ready_out` (see comment at the other `set_failed!` - # call sites in this function for why this is necessary). - Threads.atomic_sub!(state.running_count, 1) - @logfinish ctx LogSchedule LogScheduleId(state.uid, task.id) (;thunk_id=task.id) - end - return - end - # `accel` drives uniform (e.g. MPI) scheduling: it filters compatible # processors, imposes a deterministic processor order, and (under uniform # execution) makes selection ignore rank-local capacity/occupancy so every # rank picks the same processor for this task. accel = something(options.acceleration, current_acceleration()) - sorted_procs = @reusable_vector :schedule_one!_sorted_procs Processor OSProc() 32 - 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, nothing, 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. + # Lightweight placement for a task that certainly runs on a thread of this process + # (fastpath.jl); anything it does not handle takes the general path below. scheduled = false no_proc_diag = "" # filled only when no processor could be chosen, to say why in the exception local best_loc, best_spec - for proc in sorted_procs - gproc = get_parent(proc) - can_use, scope = can_use_proc(state, task, gproc, proc, options, scope) - if can_use - has_cap, est_time_util, est_alloc_util, est_occupancy = - has_capacity(state, proc, root_worker_id(gproc), options.time_util, options.alloc_util, options.occupancy, sig) - # Under uniform execution capacity is rank-local; every rank must - # take the first usable processor in the deterministic order. - if has_cap || scheduling_ignore_capacity(accel) - # Optimistic reservation: capture-the-ref, atomic_add! - counter_ref = lock(state.worker_time_pressure) do wtp - proc_map = get!(wtp, root_worker_id(gproc)) do - Dict{Processor,Threads.Atomic{UInt64}}() + fast_cand = local_fast_candidates(task, options, procs_filt, accel) + if fast_cand !== nothing + placed = local_fast_place!(state, task, options, sig, fast_cand[1], fast_cand[2]) + if placed !== nothing + best_loc, best_spec = placed + scheduled = true + end + end + + if !scheduled + # Calculate scope. Errors are stored in `scope_ex` and applied in Phase 3. + local scope + local scope_ex = nothing + if options.exec_scope !== nothing + # Bypass scope calculation if it's been done for us already + scope = options.exec_scope + else + scope = constrain(@something(options.compute_scope, options.scope, DefaultScope()), + @something(options.result_scope, AnyScope())) + if scope isa InvalidScope + scope_ex = SchedulingException("compute_scope and result_scope are not compatible: $(scope.x), $(scope.y)") + else + for arg in task.inputs + scope_ex === nothing || break + value = unwrap_weak_checked(Dagger.value(arg)) + # After collect_task_inputs!, Thunk inputs are resolved to Chunks. + @assert !istask(value) + chunk = if value isa Chunk + value + else + nothing end - get!(proc_map, proc) do - Threads.Atomic{UInt64}(UInt64(0)) + chunk isa Chunk || continue + scope = constrain(scope, chunk.scope) + if scope isa InvalidScope + scope_ex = SchedulingException("Current scope and argument Chunk scope are not compatible: $(scope.x), $(scope.y)") end end - Threads.atomic_add!(counter_ref, est_time_util) - lock(state.running_pressure_refs) do rpr - rpr[task.id] = (counter_ref, est_time_util) + end + end + + if scope_ex !== nothing + # scope is invalid — fail the task under state.lock (set_failed! requires it) + lock(state.lock) do + set_failed!(state, task; ex=scope_ex) + # Release the `running_count` credit `task` received when it + # entered `ready_out` (see comment at the other `set_failed!` + # call sites in this function for why this is necessary). + Threads.atomic_sub!(state.running_count, 1) + @logfinish ctx LogSchedule LogScheduleId(state.uid, task.id) (;thunk_id=task.id) + end + return + end + + sorted_procs = @reusable_vector :schedule_one!_sorted_procs Processor OSProc() 32 + 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, nothing, 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. + for proc in sorted_procs + gproc = get_parent(proc) + can_use, scope = can_use_proc(state, task, gproc, proc, options, scope) + if can_use + has_cap, est_time_util, est_alloc_util, est_occupancy = + has_capacity(state, proc, root_worker_id(gproc), options.time_util, options.alloc_util, options.occupancy, sig) + # Under uniform execution capacity is rank-local; every rank must + # take the first usable processor in the deterministic order. + if has_cap || scheduling_ignore_capacity(accel) + # Optimistic reservation: capture-the-ref, atomic_add! + counter_ref = lock(state.worker_time_pressure) do wtp + proc_map = get!(wtp, root_worker_id(gproc)) do + Dict{Processor,Threads.Atomic{UInt64}}() + end + get!(proc_map, proc) do + Threads.Atomic{UInt64}(UInt64(0)) + end + end + reserve_pressure!(state, task.id, counter_ref, est_time_util) + @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) + best_loc = ScheduleTaskLocation(gproc, proc) + best_spec = ScheduleTaskSpec(task, scope, est_time_util, est_alloc_util, est_occupancy) + scheduled = true + break end - @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) - best_loc = ScheduleTaskLocation(gproc, proc) - best_spec = ScheduleTaskSpec(task, scope, est_time_util, est_alloc_util, est_occupancy) - scheduled = true - break end end + if !scheduled + no_proc_diag = string(" for task ", task.id, " (", scheduling_function_name(task.f), "): ", length(sorted_procs), + " candidate processor(s) after scope ", scheduling_scope_name(scope), + ", ", length(procs_filt), " processor(s) known to this scheduler") + end + empty!(sorted_procs) end - if !scheduled - no_proc_diag = string(" for task ", task.id, " (", scheduling_function_name(task.f), "): ", length(sorted_procs), - " candidate processor(s) after scope ", scheduling_scope_name(scope), - ", ", length(procs_filt), " processor(s) known to this scheduler") - end - empty!(sorted_procs) + # Phase 3 — brief state.lock hold: fire or fail the task. # `restore_ready` only becomes non-empty if a task completes synchronously @@ -1565,6 +1602,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 +1618,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 +1635,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 +1725,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 +1855,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 +1962,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 @@ -2146,6 +2197,16 @@ end Executes a batch of tasks on `to_proc`, returning their results through `return_queue`. """ +# 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) + function do_tasks(to_proc, return_queue, tasks) @dagdebug nothing :processor "Enqueuing task batch" batch_size=length(tasks) @@ -2166,7 +2227,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 +2248,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 +2288,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/fastpath.jl b/src/sch/fastpath.jl new file mode 100644 index 000000000..8952291a0 --- /dev/null +++ b/src/sch/fastpath.jl @@ -0,0 +1,227 @@ +# Lightweight local placement. +# +# `schedule_one!` is written for the general case: candidate processors of several workers, every +# kind of processor, per-candidate capacity checks, user scopes. A task whose compatible +# processors are all CPU threads of *this* process needs none of it: nothing to rank across +# workers, no data to transfer, `has_capacity` always says yes, and every candidate accepts the +# function and its arguments. For those tasks this path takes the processors the general path +# would have used (the cached compatible set of the task's scope) and does only what still +# matters: pick the less loaded of two random candidates (all candidates when there are few), +# reserve its pressure counter, and hand the spec to phase 3. +# +# A task takes the general path whenever one of these does not hold: an option the fast path +# does not model (`proclist`, `single`, `time_util`, `alloc_util`, `occupancy`), a compute or +# result scope that is not the scope the scheduler would build itself, a chunk argument with a +# scope restriction, an acceleration other than `DistributedAcceleration` (MPI plans uniformly), +# a compatible set with any processor that is not a local `ThreadProc` (workers, GPUs, ...), or a +# function or argument type that a thread refuses. + +# Pressure counters of one scheduler's processors, aligned with `LocalFast.procs` +struct FastCounters + uid::UInt64 + refs::Vector{Threads.Atomic{UInt64}} +end + +# The compatible set of one (accel, scope) entry, when it qualifies for the fast path +mutable struct LocalFast + const procs::Vector{Dagger.ThreadProc} # all `ThreadProc`s of this process, in the compatible set's order + const gproc::OSProc + const pid::Int + @atomic counters::Union{Nothing,FastCounters} +end + +function build_local_fast(entry, accel) + accel isa Dagger.DistributedAcceleration || return nothing + compat = entry.compat + isempty(compat) && return nothing + me = myid() + procs = Vector{Dagger.ThreadProc}() + for p in compat + (p isa Dagger.ThreadProc && p.owner == me) || return nothing + push!(procs, p) + end + return LocalFast(procs, OSProc(me), me, nothing) +end + +# Stable direct-mapped slots avoid copying the whole cache on each miss. +# Entries are immutable and published atomically; a collision costs a miss. +struct FastIndexEntry + key::Tuple{UInt,UInt} + entry::CompatEntry +end +mutable struct FastIndexSlot + @atomic value::Union{Nothing,FastIndexEntry} +end +const FAST_INDEX_MAX = 2048 +const FAST_INDEX = [FastIndexSlot(nothing) for _ in 1:FAST_INDEX_MAX] +const FAST_INDEX_LOCK = ReentrantLock() +fast_index_slot(key::Tuple{UInt,UInt}) = FAST_INDEX[Int(hash(key) & UInt(FAST_INDEX_MAX - 1)) + 1] + +function invalidate_fast_index!() + lock(FAST_INDEX_LOCK) do + for slot in FAST_INDEX + @atomic :release slot.value = nothing + end + end + return +end + +function fast_compat_entry(accel, scope, procs::Vector{<:Processor}) + key = (objectid(accel), scope_key(scope)) + slot = fast_index_slot(key) + while true + cached = @atomic :acquire slot.value + if cached !== nothing && cached.key == key + entry = cached.entry + if entry.generation == COMPAT_PROCS_GENERATION[] && + entry.scope === scope && entry.procs == procs + return entry + end + end + entry = compat_entry(accel, scope, procs) + published = lock(FAST_INDEX_LOCK) do + entry.generation == COMPAT_PROCS_GENERATION[] || return false + @atomic :release slot.value = FastIndexEntry(key, entry) + return true + end + published && return entry + end +end + +# `entry.fast` is `missing` until first asked +function local_fast_of(entry, accel) + fast = @atomic entry.fast + if fast === missing + fast = build_local_fast(entry, accel) + @atomic entry.fast = fast + end + return fast::Union{Nothing,LocalFast} +end + +# What the scheduler builds for a task without any scope of its own; computed once +const UNSCOPED_SCOPE = Ref{Union{Nothing,Dagger.AbstractScope}}(nothing) +function unscoped_scope() + scope = UNSCOPED_SCOPE[] + if scope === nothing + scope = constrain(DefaultScope(), AnyScope()) + UNSCOPED_SCOPE[] = scope + end + return scope::Dagger.AbstractScope +end + +""" + local_fast_candidates(task, options, procs, accel) -> Union{Nothing,Tuple{LocalFast,AbstractScope}} + +The fast path's candidate set and the scope the task is scheduled under, or `nothing` when the +task must take the general path (see the file header). The caller has already filtered `procs` +to workers registered with the scheduler. This function reserves nothing. +""" +function local_fast_candidates(task, options, procs, accel)::Union{Nothing,Tuple{LocalFast,Dagger.AbstractScope}} + (options.proclist === nothing && options.single === nothing && options.time_util === nothing && + options.alloc_util === nothing && options.occupancy === nothing) || return nothing + accel isa Dagger.DistributedAcceleration || return nothing + exec = options.exec_scope + if exec !== nothing + # The scope was fixed by the caller (Datadeps): it is used as is + fast = local_fast_of(fast_compat_entry(accel, exec, procs), accel) + fast === nothing && return nothing + return (fast, exec) + end + if options.compute_scope === nothing && options.scope === nothing && options.result_scope === nothing + for arg in task.inputs + value = unwrap_weak_checked(Dagger.value(arg)) + # A chunk with a scope restriction narrows the candidates + value isa Chunk && !(value.scope isa AnyScope) && return nothing + end + scope = unscoped_scope() + fast = local_fast_of(fast_compat_entry(accel, scope, procs), accel) + fast === nothing && return nothing + return (fast, scope) + end + return nothing +end + +function build_fast_counters!(state, fast::LocalFast) + refs = Vector{Threads.Atomic{UInt64}}(undef, length(fast.procs)) + lock(state.worker_time_pressure) + try + wtp = Dagger.payload(state.worker_time_pressure) + proc_map = get!(wtp, fast.pid) do + Dict{Processor,Threads.Atomic{UInt64}}() + end + for idx in eachindex(fast.procs) + refs[idx] = get!(proc_map, fast.procs[idx]) do + Threads.Atomic{UInt64}(UInt64(0)) + end + end + finally + unlock(state.worker_time_pressure) + end + counters = FastCounters(state.uid, refs) + @atomic fast.counters = counters + return counters +end + +# The index of the candidate to run on: what the general path's ranking would put first. The +# counters are read without a lock (they are atomics). +function pick_fast_candidate(refs::Vector{Threads.Atomic{UInt64}}) + np = length(refs) + np == 1 && return 1 + if np > TWO_CHOICES_MIN + i1 = rand(1:np) + i2 = rand(1:np-1) + i2 >= i1 && (i2 += 1) + return @inbounds(refs[i2][]) < @inbounds(refs[i1][]) ? i2 : i1 + end + # Few candidates: the least loaded, a tie broken uniformly at random + best = typemax(UInt64) + idx = 1 + nties = 0 + for i in 1:np + c = @inbounds(refs[i][]) + if c < best + best = c + idx = i + nties = 1 + elseif c == best + nties += 1 + rand(1:nties) == 1 && (idx = i) + end + end + return idx +end + +""" + local_fast_place!(state, task, options, sig, fast, scope) -> Union{Nothing,Tuple{ScheduleTaskLocation,ScheduleTaskSpec}} + +Chooses a processor of `fast` for `task` and reserves its pressure counter. `nothing` (with +nothing reserved) when a thread would refuse the function or an argument: the general path then +decides. +""" +function local_fast_place!(state, task, options, sig, fast::LocalFast, scope) + counters = @atomic fast.counters + if counters === nothing || counters.uid != state.uid + counters = build_fast_counters!(state, fast) + end + refs = counters.refs + idx = pick_fast_candidate(refs) + proc = @inbounds fast.procs[idx]::Dagger.ThreadProc + # Compatibility hooks can inspect the processor instance, including its tid. + inputs = task.inputs + Dagger.iscompatible_func(proc, options, chunktype(task.f)) || return nothing + for idx in 2:length(inputs) + value = unwrap_weak_checked(Dagger.value(@inbounds inputs[idx])) + value isa Thunk && return nothing + Dagger.iscompatible_arg(proc, options, chunktype(value)) || return nothing + end + + has_cap, est_time_util, est_alloc_util, est_occupancy = + has_capacity(state, proc, fast.pid, nothing, nothing, nothing, sig) + has_cap || return nothing + + counter_ref = @inbounds refs[idx] + reserve_pressure!(state, task.id, counter_ref, est_time_util) + loc = ScheduleTaskLocation(fast.gproc, proc) + spec = ScheduleTaskSpec(task, scope, est_time_util, est_alloc_util, est_occupancy) + return (loc, spec) +end diff --git a/src/sch/util.jl b/src/sch/util.jl index 50a7a6d1c..4f74fc486 100644 --- a/src/sch/util.jl +++ b/src/sch/util.jl @@ -615,6 +615,19 @@ function has_capacity(state, p, gp, time_util, alloc_util, occupancy, sig) return true, est_time_util, est_alloc_util, est_occupancy end +# Both placement paths reserve through this operation so completion always +# releases the exact counter and estimate that placement credited. +function reserve_pressure!(state, task_id::Int, counter_ref::Threads.Atomic{UInt64}, est::UInt64) + Threads.atomic_add!(counter_ref, est) + lock(state.running_pressure_refs) + try + Dagger.payload(state.running_pressure_refs)[task_id] = (counter_ref, est) + finally + unlock(state.running_pressure_refs) + end + return counter_ref +end + "Like `sum`, but replaces `nothing` entries with the average of non-`nothing` entries." function impute_sum(xs) total = 0 @@ -773,11 +786,112 @@ 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 + +# With many candidates that are all threads of one process, the cost of a candidate is its +# reserved pressure and nothing else (same-worker transfers are free, `est_time_util` is the +# same for every candidate), so ranking all of them reads every counter, shuffles and sorts: +# O(threads) work per task that grew to ~50 us at 64 threads on our cluster. The scheduler only +# needs a good first choice, because idle runners steal what is queued behind a busy one. +# Choose the less loaded of two random candidates instead ("power of two choices": the +# maximum load stays within O(log log n) of the mean), and keep the rest in rotation order as +# fallbacks for the capacity checks. +const TWO_CHOICES_MIN = 8 # candidates + +# The pid shared by every candidate, or -1 +function single_worker_pid(procs, ::Type{P}) where {P} + pid = Dagger.root_worker_id(@inbounds(procs[1])::P) + for idx in 2:length(procs) + Dagger.root_worker_id(@inbounds(procs[idx])::P) == pid || return -1 + end + return pid +end + +# Compute-only ranking is valid for same-worker CPU threads. Other processor +# kinds may have distinct memory spaces and transfer costs even on one worker. +two_choices_pid(procs) = candidate_type(procs) === Dagger.ThreadProc ? + single_worker_pid(procs, Dagger.ThreadProc) : -1 + +function place_two_choices!(sorted_procs, state, procs, np::Int, pid::Int) + i1 = rand(1:np) + i2 = rand(1:np-1) + i2 >= i1 && (i2 += 1) + p1 = @inbounds procs[i1] + p2 = @inbounds procs[i2] + # One acquisition for both counters. N.B. Explicit lock/unlock, and the result returned + # from the `try`, so nothing is captured and reassigned (which would box it). + lock(state.worker_time_pressure) + c1, c2 = try + wtp = Dagger.payload(state.worker_time_pressure) + proc_map = get(wtp, pid, nothing) + if proc_map === nothing + (UInt64(0), UInt64(0)) + else + r1 = get(proc_map, p1, nothing) + r2 = get(proc_map, p2, nothing) + (r1 === nothing ? UInt64(0) : r1[], r2 === nothing ? UInt64(0) : r2[]) + end + finally + unlock(state.worker_time_pressure) + end + first_idx, second_idx = c2 < c1 ? (i2, i1) : (i1, i2) + @inbounds sorted_procs[1] = procs[first_idx] + @inbounds sorted_procs[2] = procs[second_idx] + pos = 3 + off = rand(1:np) + for k in 1:np + j = off + k + j > np && (j -= np) + (j == first_idx || j == second_idx) && continue + @inbounds sorted_procs[pos] = procs[j] + pos += 1 + 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. @@ -800,6 +914,14 @@ candidate lookups cost about 130 us for 16 threads and grew with the thread coun return end + if costs === nothing && np > TWO_CHOICES_MIN + pid = two_choices_pid(procs) + if pid >= 0 + place_two_choices!(sorted_procs, state, procs, np, pid) + return + end + end + # Find all Chunks chunks = @reusable_vector :estimate_task_costs_chunks Union{Chunk,Nothing} nothing 32 for input in task.inputs @@ -871,9 +993,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/local-fastpath.jl b/test/local-fastpath.jl new file mode 100644 index 000000000..f577f2d11 --- /dev/null +++ b/test/local-fastpath.jl @@ -0,0 +1,324 @@ +using Dagger, Test, LinearAlgebra, Random +using .Distributed +import Dagger: ThreadProc, Processor +import Dagger.Sch: COMPAT_PROCS_CACHE + +# With workers, unscoped tasks may run anywhere (and take the general path), so the code the tasks +# run exists everywhere; what the fast path decides is checked where it can be seen, on one process. +@everywhere begin + using Dagger + struct NoThreadFn end + (::NoThreadFn)(x) = x + Dagger.iscompatible_func(::Dagger.ThreadProc, opts, ::Type{NoThreadFn}) = false + FP_TINY(x) = x + 1 + struct NoThreadArg end + FP_TINY(::NoThreadArg) = :kernel_would_accept_this_argument + Dagger.iscompatible_arg(::Dagger.ThreadProc, opts, ::Type{NoThreadArg}) = false + struct FirstThreadFn end + (::FirstThreadFn)() = Dagger.task_processor() + Dagger.iscompatible_func(proc::ThreadProc, opts, ::Type{FirstThreadFn}) = proc.tid == 1 + struct FirstThreadArg end + Dagger.iscompatible_arg(proc::ThreadProc, opts, ::Type{FirstThreadArg}) = proc.tid == 1 + fp_proc() = (sleep(0.002); Dagger.task_processor()) +end + +# A compatible-set computation paused across a simulated hierarchy change. +mutable struct PausedCompatScope <: Dagger.AbstractScope + current::Vector{Processor} + entered::Base.Event + release::Base.Event + pause::Bool +end +function Dagger.compatible_processors(::Dagger.DistributedAcceleration, scope::PausedCompatScope, + ::Vector{<:Processor}) + result = Set{Processor}(scope.current) + if scope.pause + scope.pause = false + notify(scope.entered) + wait(scope.release) + end + return result +end + +@testset "In-flight compatible sets cannot survive invalidation" begin + accel = Dagger.DistributedAcceleration() + old_proc = ThreadProc(myid(), 1) + new_proc = ThreadProc(myid(), 2) + scope = PausedCompatScope(Processor[old_proc], Base.Event(), Base.Event(), true) + procs = Processor[Dagger.OSProc(myid())] + Dagger.Sch.invalidate_compat_procs_cache!() + lookup = Threads.@spawn Dagger.Sch.fast_compat_entry(accel, scope, procs) + @test timedwait(() -> scope.entered.set, 30) == :ok + scope.current = Processor[new_proc] + Dagger.Sch.invalidate_compat_procs_cache!() + notify(scope.release) + @test timedwait(() -> istaskdone(lookup), 30) == :ok + if istaskdone(lookup) + @test fetch(lookup).compat == Set{Processor}([new_proc]) + @test Dagger.Sch.fast_compat_entry(accel, scope, procs).compat == Set{Processor}([new_proc]) + end + Dagger.Sch.invalidate_compat_procs_cache!() +end + +# The fast path's view of every cached compatible set that qualified +fast_entries() = count(e -> e.fast isa Dagger.Sch.LocalFast, values(Dagger.payload(COMPAT_PROCS_CACHE).cache)) + +# Total reserved pressure of the eager scheduler; zero once everything has finished. Every counter is +# checked on its own: a release without a matching reservation wraps a counter around to a huge value, +# which a plain sum could cancel against another counter. +function reserved_pressure() + state = Dagger.Sch.EAGER_STATE[] + total = UInt64(0) + lock(state.worker_time_pressure) do wtp + for pm in values(wtp), c in values(pm) + c[] == 0 || (total = max(total, c[])) + end + end + return total +end + +@testset "Local fast path" begin + begin + @testset "tasks complete and release their pressure" begin + Dagger.Sch.invalidate_compat_procs_cache!() + ts = [Dagger.@spawn FP_TINY(i) for i in 1:500] + @test sum(fetch.(ts)) == sum(2:501) + Dagger.@spawn(FP_TINY(0)) |> fetch # one more so the last completions have been handled + # unscoped tasks on a plain process qualify (with workers they may run anywhere) + nprocs() == 1 && @test fast_entries() >= 1 + sleep(0.2) + @test reserved_pressure() == 0 + end + + @testset "placement spreads over the threads" begin + nt = Threads.nthreads() + if nt > 1 && nprocs() == 1 + ps = Set{Processor}(fetch.([Dagger.@spawn fp_proc() for _ in 1:20 * nt])) + @test length(ps) >= min(nt, 4) + @test all(p -> p isa ThreadProc && p.owner == myid(), ps) + end + end + + @testset "options the fast path does not model take the general path" begin + @test fetch(Dagger.@spawn proclist=[ThreadProc] FP_TINY(1)) == 2 + @test fetch(Dagger.@spawn single=1 FP_TINY(1)) == 2 + @test fetch(Dagger.@spawn occupancy=Dict(ThreadProc=>0.5) FP_TINY(3)) == 4 + @test fetch(Dagger.@spawn time_util=Dict(ThreadProc=>1_000_000) FP_TINY(4)) == 5 + @test fetch(Dagger.@spawn alloc_util=Dict(ThreadProc=>UInt64(1024)) FP_TINY(5)) == 6 + # a scope is honoured + p = fetch(Dagger.@spawn scope=Dagger.scope(worker=myid(), thread=1) fp_proc()) + @test p == ThreadProc(myid(), 1) + # so is a scope on a chunk argument + ch = Dagger.tochunk(5, ThreadProc(myid(), 1), Dagger.ExactScope(ThreadProc(myid(), 1))) + @test fetch(Dagger.@spawn FP_TINY(ch)) == 6 + end + + @testset "scopes naming some threads are honoured" begin + nt = Threads.nthreads() + rng = MersenneTwister(7) + for _ in 1:80 + k = rand(rng, 1:min(nt, 4)) + tids = sort!(randperm(rng, nt)[1:k]) + sc = rand(rng, Bool) ? Dagger.scope(worker=myid(), threads=tids) : + Dagger.UnionScope(map(t -> Dagger.ExactScope(ThreadProc(myid(), t)), tids)) + ts = [Dagger.with_options(scope=sc) do; Dagger.@spawn fp_proc(); end for _ in 1:4] + @test all(p -> p isa ThreadProc && p.owner == myid() && p.tid in tids, fetch.(ts)) + end + # many small tasks pinned to a thread subset, some of them consuming earlier results + sc = Dagger.scope(worker=myid(), threads=1:min(nt, 2)) + first_ts = [Dagger.with_options(scope=sc) do; Dagger.@spawn fp_proc(); end for _ in 1:50] + second_ts = [Dagger.with_options(scope=sc) do; Dagger.@spawn identity(t); end for t in first_ts] + @test all(p -> p.tid in 1:min(nt, 2), fetch.(second_ts)) + sleep(0.2) + @test reserved_pressure() == 0 + end + + @testset "a thread that refuses an argument type is respected" begin + t = Dagger.@spawn FP_TINY(NoThreadArg()) + @test_throws_unwrap (Dagger.DTaskFailedException, Dagger.Sch.SchedulingException) reason < "No processors available" fetch(t) + end + + @testset "a thread that refuses the function is respected" begin + t = Dagger.@spawn NoThreadFn()(1) + @test_throws Exception fetch(t) + end + + @testset "Datadeps" begin + A = [zeros(8) for _ in 1:12] + Dagger.spawn_datadeps() do + for a in A + Dagger.@spawn fill!(Dagger.InOut(a), 3.0) + end + for a in A + Dagger.@spawn rmul!(Dagger.InOut(a), 2.0) + end + end + @test all(a -> all(==(6.0), a), A) + end + end +end + +@everywhere begin + FP_PROCARG(x) = (sleep(0.002); Dagger.task_processor()) +end + +# Pressure counters aligned like `LocalFast.refs` +struct FPOtherAccel <: Dagger.Acceleration end +fp_refs(v) =[Threads.Atomic{UInt64}(UInt64(x)) for x in v] +function fast_values() + entries = Dagger.Sch.CompatEntry[] + for slot in Dagger.Sch.FAST_INDEX + cached = @atomic slot.value + cached === nothing || push!(entries, cached.entry) + end + return entries +end + +@testset "Local fast path: decisions" begin + LocalFast = Dagger.Sch.LocalFast + me = myid() + accel = Dagger.DistributedAcceleration() + + @testset "only a compatible set made of this process's threads qualifies" begin + local_set = Processor[ThreadProc(me, 1), ThreadProc(me, 2)] + @test Dagger.Sch.build_local_fast((; compat=local_set), accel) isa LocalFast + @test Dagger.Sch.build_local_fast((; compat=Processor[]), accel) === nothing + # a thread of another worker + @test Dagger.Sch.build_local_fast((; compat=Processor[ThreadProc(me, 1), ThreadProc(me + 1, 1)]), accel) === nothing + # a processor that is not a thread + @test Dagger.Sch.build_local_fast((; compat=Processor[ThreadProc(me, 1), FakeProc()]), accel) === nothing + # only the distributed acceleration is handled + @test Dagger.Sch.build_local_fast((; compat=local_set), FPOtherAccel()) === nothing + end + + @testset "the fast path places tasks" begin + if nprocs() == 1 + Dagger.Sch.invalidate_compat_procs_cache!() + @test !any(e -> e.fast isa LocalFast && (@atomic e.fast.counters) !== nothing, fast_values()) + fetch.([Dagger.@spawn FP_TINY(i) for i in 1:50]) + @test any(e -> e.fast isa LocalFast && (@atomic e.fast.counters) !== nothing, fast_values()) + end + end + + @testset "compatibility is checked on the selected thread" begin + # Force the chooser to select the second thread, which refuses these + # inputs. The fast path should leave pressure untouched and fall back. + procs = Processor[ThreadProc(me, 1), ThreadProc(me, 2)] + refs = fp_refs([1, 0]) + uid = UInt64(1) + fast = LocalFast(procs, Dagger.OSProc(me), me, Dagger.Sch.FastCounters(uid, refs)) + reservations = Dict{Int,Tuple{Threads.Atomic{UInt64},UInt64}}() + state = (; uid, + signature_time_cost=Dagger.LockedObject(Dict{Any,UInt64}()), + signature_alloc_cost=Dagger.LockedObject(Dict{Any,UInt64}()), + running_pressure_refs=Dagger.LockedObject(reservations)) + opts = Dagger.Options() + scope = Dagger.DefaultScope() + @test Dagger.Sch.local_fast_place!(state, Dagger.Thunk(FirstThreadFn(); options=opts), + opts, :func, fast, scope) === nothing + @test Dagger.Sch.local_fast_place!(state, Dagger.Thunk(FP_PROCARG, nothing => FirstThreadArg(); options=opts), + opts, :arg, fast, scope) === nothing + @test [r[] for r in refs] == [1, 0] + @test isempty(reservations) + end + + @testset "options the fast path does not model are not decided by it" begin + if nprocs() == 1 + for (name, f) in (("proclist", () -> Dagger.@spawn proclist=[ThreadProc] FP_TINY(1)), + ("single", () -> Dagger.@spawn single=1 FP_TINY(1)), + ("occupancy", () -> Dagger.@spawn occupancy=Dict(ThreadProc=>0.5) FP_TINY(1)), + ("time_util", () -> Dagger.@spawn time_util=Dict(ThreadProc=>1_000_000) FP_TINY(1)), + ("alloc_util", () -> Dagger.@spawn alloc_util=Dict(ThreadProc=>UInt64(1024)) FP_TINY(1))) + Dagger.Sch.invalidate_compat_procs_cache!() + @test fetch(f()) == 2 + @test !any(e -> e.fast isa LocalFast && (@atomic e.fast.counters) !== nothing, fast_values()) + end + end + end + + @testset "a scope restriction on a chunk argument is honoured" begin + nt = Threads.nthreads() + if nt > 1 + tp = ThreadProc(me, nt) + ch = Dagger.tochunk(5, tp, Dagger.ExactScope(tp)) + ps = fetch.([Dagger.@spawn FP_PROCARG(ch) for _ in 1:40]) + @test all(==(tp), ps) + end + end + + @testset "with workers, unscoped tasks also run on other workers" begin + if nprocs() > 1 + owners = Set(p.owner for p in fetch.([Dagger.@spawn fp_proc() for _ in 1:120])) + @test length(owners) > 1 + end + end + + @testset "pick_fast_candidate chooses the less loaded thread" begin + pick = Dagger.Sch.pick_fast_candidate + @test pick(fp_refs([5])) == 1 + # up to TWO_CHOICES_MIN candidates: always the least loaded + refs8 = fp_refs([5, 9, 0, 7, 3, 8, 6, 4]) + @test length(refs8) == Dagger.Sch.TWO_CHOICES_MIN + @test all(_ -> pick(refs8) == 3, 1:300) + # ties are broken at random + @test length(Set(pick(fp_refs(zeros(Int, 8))) for _ in 1:400)) == 8 + # more candidates: two random ones are compared. The most loaded never wins, the least + # loaded wins when it is drawn, and it is not always the one picked + refs9 = fp_refs([5, 9, 0, 7, 3, 8, 6, 4, 2]) + picks = [pick(refs9) for _ in 1:3000] + @test 2 ∉ picks + @test 3 in picks + @test any(!=(3), picks) + end + + @testset "candidate ranking switches to two choices above TWO_CHOICES_MIN" begin + # One heavily loaded thread among n. The full ranking selects the PLACEMENT_SELECT cheapest + # exactly, so the loaded one is never among the first places; two choices compares only two + # random candidates, so the loaded one is the second place whenever it is drawn + busy_early(n) = begin + procs = Processor[ThreadProc(me, t) for t in 1:n] + pressure = Dict{Processor,Threads.Atomic{UInt64}}(p => Threads.Atomic{UInt64}(UInt64(p === procs[1] ? 10^9 : 0)) for p in procs) + state = (; worker_time_pressure=Dagger.LockedObject(Dict{Int,Dict{Processor,Threads.Atomic{UInt64}}}(me => pressure)), + signature_time_cost=Dagger.LockedObject(Dict{Any,Any}()), + worker_transfer_rate=Dagger.LockedObject(Dict{Any,Any}())) + task = (; inputs=Any[], f=identity) + sorted = Vector{Processor}(undef, n) + early = 0 + for _ in 1:300 + Dagger.Sch.estimate_task_costs!(sorted, nothing, state, procs, task; sig=:sig) + early += findfirst(==(procs[1]), sorted) <= Dagger.Sch.PLACEMENT_SELECT + @test sorted[1] !== procs[1] + end + early + end + @test busy_early(Dagger.Sch.TWO_CHOICES_MIN) == 0 + @test busy_early(Dagger.Sch.TWO_CHOICES_MIN + 1) > 0 + end + + @testset "the lock-free snapshot is bounded and follows invalidation" begin + procs = Processor[ThreadProc(me, 1)] + Dagger.Sch.invalidate_compat_procs_cache!() + @test all(slot -> (@atomic slot.value) === nothing, Dagger.Sch.FAST_INDEX) + fetch(Dagger.@spawn FP_TINY(1)) + nprocs() == 1 && @test !all(slot -> (@atomic slot.value) === nothing, Dagger.Sch.FAST_INDEX) + Dagger.Sch.invalidate_compat_procs_cache!() + @test all(slot -> (@atomic slot.value) === nothing, Dagger.Sch.FAST_INDEX) + scopes = [Dagger.ExactScope(ThreadProc(me, t)) for t in 1:(Dagger.Sch.FAST_INDEX_MAX + 50)] + entries = [Dagger.Sch.fast_compat_entry(accel, sc, procs) for sc in scopes] + # More keys than slots replace collisions but still return exact entries. + @test all(i -> entries[i].scope === scopes[i], eachindex(scopes)) + @test length(Dagger.Sch.FAST_INDEX) == Dagger.Sch.FAST_INDEX_MAX + # Force a collision with a different scope under the requested key. + scope = first(scopes) + key = (objectid(accel), Dagger.Sch.scope_key(scope)) + slot = Dagger.Sch.fast_index_slot(key) + @atomic :release slot.value = Dagger.Sch.FastIndexEntry(key, last(entries)) + @test Dagger.Sch.fast_compat_entry(accel, scope, procs).scope === scope + current = Dagger.Sch.fast_compat_entry(accel, scope, procs) + stale = Dagger.Sch.CompatEntry(current.generation - UInt(1), current.scope, + current.procs, current.compat, nothing, missing) + @atomic :release slot.value = Dagger.Sch.FastIndexEntry(key, stale) + @test Dagger.Sch.fast_compat_entry(accel, scope, procs) !== stale + Dagger.Sch.invalidate_compat_procs_cache!() + end +end diff --git a/test/runtests.jl b/test/runtests.jl index bd2507e59..b2ac1e5f9 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -22,6 +22,8 @@ tests = [ ("Scheduler", "scheduler.jl"), ("Processors", "processors.jl"), ("Uniform Placement", "uniform-placement.jl"), + ("Two-choices Placement", "two-choices.jl"), + ("Local Fast Path", "local-fastpath.jl"), ("Processor Grids", "procgrid.jl"), ("Memory Spaces", "memory-spaces.jl"), ("Logging", "logging.jl"), 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 diff --git a/test/two-choices.jl b/test/two-choices.jl new file mode 100644 index 000000000..85313fec6 --- /dev/null +++ b/test/two-choices.jl @@ -0,0 +1,56 @@ +using Dagger, Test +using .Distributed +import Dagger: ThreadProc, Processor, LockedObject + +struct NonThreadCandidate <: Processor + owner::Int + index::Int +end +Dagger.get_parent(proc::NonThreadCandidate) = Dagger.OSProc(proc.owner) + +@testset "Two-choices placement" begin + pid = myid() + nproc = 16 + procs = Processor[ThreadProc(pid, t) for t in 1:nproc] + busy = procs[5] + pressure = Dict{Processor,Threads.Atomic{UInt64}}(p => Threads.Atomic{UInt64}(UInt64(p === busy ? 10^9 : 0)) for p in procs) + state = (; worker_time_pressure=LockedObject(Dict{Int,Dict{Processor,Threads.Atomic{UInt64}}}(pid => pressure))) + sorted = Vector{Processor}(undef, nproc) + firsts = Set{Processor}() + for _ in 1:3000 + Dagger.Sch.place_two_choices!(sorted, state, procs, nproc, pid) + # a permutation of the candidates + @test length(unique(sorted)) == nproc + @test Set(sorted) == Set(procs) + # the loaded processor never wins a comparison, so it is never first + @test sorted[1] !== busy + push!(firsts, sorted[1]) + end + # every other processor is a possible first choice (the choice is random, not fixed) + @test length(firsts) == nproc - 1 + + # a processor with less pressure than its competitor is placed ahead of it + for p in procs; pressure[p][] = UInt64(0); end + pressure[procs[1]][] = UInt64(7) + for _ in 1:500 + Dagger.Sch.place_two_choices!(sorted, state, procs, nproc, pid) + @test findfirst(==(procs[1]), sorted) >= 2 # worse than every other processor it is compared with + end + + # no table for this worker yet: still a valid order + empty_state = (; worker_time_pressure=LockedObject(Dict{Int,Dict{Processor,Threads.Atomic{UInt64}}}())) + Dagger.Sch.place_two_choices!(sorted, empty_state, procs, nproc, pid) + @test Set(sorted) == Set(procs) + + @test Dagger.Sch.two_choices_pid(procs) == pid + devices = Processor[NonThreadCandidate(pid, i) for i in 1:16] + @test Dagger.Sch.two_choices_pid(devices) == -1 + @test Dagger.Sch.two_choices_pid(Processor[procs[1:8]..., devices[1:8]...]) == -1 + + # candidates of two workers use the full ranking path + @test Dagger.Sch.single_worker_pid(procs, Processor) == pid + if nprocs() > 1 + mixed = Processor[ThreadProc(pid, 1), ThreadProc(first(workers()), 1)] + @test Dagger.Sch.single_worker_pid(mixed, Processor) == -1 + end +end