Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/src/scheduler-internals.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
18 changes: 17 additions & 1 deletion src/datadeps/queue.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
118 changes: 107 additions & 11 deletions src/sch/Sch.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand All @@ -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"
Expand All @@ -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
Expand Down Expand Up @@ -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

Expand Down
54 changes: 49 additions & 5 deletions src/sch/util.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading