Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
c0c8f63
Datadeps: give every processor of a space the same union scope object
AnnaLena77 Nov 21, 2026
af84a49
Sch: key the compatible-processor cache of a large union scope by a c…
AnnaLena77 Nov 21, 2026
c32b04d
perf: rank only the cheapest placement candidates instead of sorting …
AnnaLena77 Nov 21, 2026
808790c
Sched: wake only the runners that can take the enqueued task
AnnaLena77 Nov 21, 2026
54991c9
Sched: do not read a TaskSpec after handing it to the queue
AnnaLena77 Nov 21, 2026
bac8442
sched: place on the less loaded of two random threads when one proces…
AnnaLena77 Nov 26, 2026
2c32c8c
Sch: lightweight placement for tasks that run on a thread of this pro…
AnnaLena77 Nov 26, 2026
b40b4b2
Sch: read the fast path's compatible sets from a lock-free snapshot
AnnaLena77 Oct 25, 2026
0aab580
sched: uniform placement reads the compatible set from the lock-free …
AnnaLena77 Oct 26, 2026
3be72dc
test: local fast path decisions
AnnaLena77 Nov 27, 2026
0443836
Use the selected Distributed transport in placement tests
jpsamaroo Nov 29, 2026
6fb2012
Check the selected thread's compatibility before reserving it
jpsamaroo Nov 29, 2026
39de00d
Use the locked worker snapshot for local placement
jpsamaroo Nov 29, 2026
c3269ee
Merge master into pr/b1-local-fastpath
jpsamaroo Nov 30, 2026
d8fd8dd
Bound mixed-scope wakeup filtering and read occupancy under its lock
jpsamaroo Nov 30, 2026
24b106d
Describe the scheduler's partial candidate ranking accurately
jpsamaroo Nov 30, 2026
663ead2
Reject compatible-set publications that cross invalidation
jpsamaroo Nov 30, 2026
926574f
Publish fast compatible entries in fixed atomic slots
jpsamaroo Nov 30, 2026
54697bc
Give every tied cheapest candidate equal selection weight
jpsamaroo Nov 30, 2026
3c371a9
Explain approximate local and partial candidate placement
jpsamaroo Nov 30, 2026
7cf1c1a
Keep device candidates on the general placement cost path
jpsamaroo Nov 30, 2026
c2878dc
Verify stale-generation fast entries are rejected on lookup
jpsamaroo Nov 30, 2026
bcba49d
Keep wakeup filtering selective for small large-pool batches
jpsamaroo Nov 30, 2026
e30e017
Match scheduling refusal without freezing diagnostic details
jpsamaroo Nov 30, 2026
f48c01d
Share task estimates and pressure reservation across placement paths
jpsamaroo Nov 30, 2026
5c8fb51
Bound best-effort scope sharing across unrelated spaces
jpsamaroo Nov 30, 2026
4de82ff
Record the generation boundary for multi-layer cache invalidation
jpsamaroo Nov 30, 2026
4cfc21b
Preserve safe scope diagnostics on the local-placement fallback
jpsamaroo Nov 30, 2026
27d7c62
Describe two-choice ranking on remote CPU workers too
jpsamaroo Nov 30, 2026
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
9 changes: 9 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
15 changes: 14 additions & 1 deletion docs/src/scheduler-internals.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
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
399 changes: 258 additions & 141 deletions src/sch/Sch.jl

Large diffs are not rendered by default.

227 changes: 227 additions & 0 deletions src/sch/fastpath.jl
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading