Skip to content

Scheduler: place tasks that run on a thread of this process with a short path - #814

Open
AnnaLena77 wants to merge 29 commits into
JuliaParallel:masterfrom
AnnaLena77:pr/b1-local-fastpath
Open

AnnaLena77 wants to merge 29 commits into
JuliaParallel:masterfrom
AnnaLena77:pr/b1-local-fastpath

Conversation

@AnnaLena77

Copy link
Copy Markdown
Collaborator

Category 2 (adapted internal functionality, scheduler placement), local fast placement:
A change inside the scheduler's task placement (schedule_one!, estimate_task_costs!). No API change. It
adds a short path for tasks that can only run on a thread of this process, and a cheaper way to choose a
thread when there are many.

Based on open PR #806 (bundle/b5-placement).

Decision for the maintainer. The fast path is always on (no switch), and the two-choice threshold is a
constant, TWO_CHOICES_MIN = 8. The fast path only skips work: it uses the compatible set the general path
would use and falls back to the general path whenever it cannot decide (see Change), so it never changes where
a task may run.

Problem. schedule_one! is written for the general case: candidates on several workers, all kinds of
processors, per-candidate capacity checks. For a task whose compatible processors are all CPU threads of this
process none of that matters, but the task still pays for ranking every candidate. The compatible-set cache is
also one frequency-ordered cache behind one lock.

Change.

  1. Two choices (src/sch/util.jl): with more than 8 candidates, all threads of one worker and no
    per-candidate cost wanted, sample two candidates and take the one with less reserved pressure; the rest stay
    in rotation order as fallbacks.
  2. Local fast path (src/sch/fastpath.jl): take the cached compatible set, pick the less loaded of two random
    threads (the least loaded when there are 8 or fewer), reserve the pressure counter and hand the spec on.
    General path for proclist, single, time_util, alloc_util, occupancy, a compute or result scope,
    chunk arguments with a scope restriction, any acceleration but DistributedAcceleration, any non-local or
    non-ThreadProc member, a Thunk argument still unresolved, and when a thread refuses the function or an
    argument type. With Distributed workers an unscoped task has remote candidates and therefore takes the
    general path.
  3. Lock-free snapshot: the fast path reads CompatEntrys from a dictionary that is replaced, not mutated
    (bounded to 2048 keys, emptied when the processor hierarchy changes).
  4. compatible_processors_ordered (uniform placement) uses the same snapshot.

Effect. Single process, one node of our cluster (64 cores), Julia 1.13.1, three interleaved rounds,
medians (2026-11-27). Against bundle/b5-placement (#806): @spawn at 16 threads 124 -> 81 us per task, at 64
threads 167 -> 126 us; Dagger cholesky! 8192/256 at 64 threads 2.39 -> 1.56 s, at 16 threads 1.87 -> 1.82 s
(ranges 1.82-1.94 and 1.73-1.84, overlapping). Against upstream master the same run gives 188 -> 81 us and
927 -> 126 us for @spawn, and 5.84 -> 1.56 s for the 64-thread Cholesky, which includes #806. Earlier
numbers, not re-measured: laptop 16 threads plain @spawn 36 -> 16 us for the two choices alone; candidate
lookup of a fast-path task 3.9 us at 16 threads and 11.7 us at 64 before the snapshot; uniform placement under
MPI, one rank, 4 threads, plain @spawn 15.32 -> 14.2 us.

Switches dropped. The development switches JULIA_DAGGER_LOCAL_FASTPATH and JULIA_DAGGER_TWO_CHOICES_MIN are gone.
The tests no longer toggle a flag; the two-choices test calls place_two_choices! directly.

Testing (local macOS, Julia 1.13). scheduler (40282 pass / 5 broken), thunk, options, datadeps,
two-choices (9504), local-fastpath (93): scheduler and local-fastpath at -t 1, -t 2 and -t 4, and
scheduler, local-fastpath, two-choices, datadeps (2142 / 2 broken), thunk and options with -p 3 -t 2, all run on the
tip of a build that also contains two follow-up scheduler commits that are not part of this PR (scheduler 40290 / 5 broken); Allocations 25/25 in a
fresh process. test/local-fastpath.jl additionally checks, with random thread subsets given as scope(threads=...)
and as unions of ExactScopes, that every task runs on a permitted thread, and, counter by counter (a sum
could hide a wrapped counter), that all reserved pressure is released. Full MPI test/mpi/cpu.jl at 2 ranks x 2 threads
on this tip: 1132/1132 and 1132/1132 pass, no failures. The fast path is checked for use only on one process (nprocs() == 1).
Not run: GPU, multi-node MPI, Julia 1.10.

AI disclosure: I prepared this change with the help of Claude (Anthropic) and reviewed it myself.
🤖 Generated with Claude Code

The scope Datadeps hands each task depends on the processor only through its
memory space, but get! built one UnionScope per processor, equal in content.
The scheduler's compatible-set lookup then ended every hit in a member-by-
member comparison of 64 scopes: 22 us per task at 64 threads on our cluster (flat
Datadeps Cholesky 8192/256; 1.3 us on a laptop, the cluster's cores are ~7x
slower per primitive). The first processor's scope is now shared with the
others (share_equal_scope), so the comparison is a pointer test.
…heap content key

objectid of a UnionScope hashes every member; Datadeps hands each task a
union of one ExactScope per thread, so the cache lookup cost O(threads) per
task (measured on our cluster, flat Datadeps Cholesky 8192/256: 11.4 us at 16
threads, 39.9 us at 64 threads, of ~190 us per schedule_one!). A union of
more than 8 scopes is keyed by its length and its first and last member,
which stays a function of the contents: the equal union a later Datadeps
region builds finds the earlier region's entry. (A key by address looks
cheaper but pollutes the frequency-ordered cache with 64 never-hit entries
per region; once it is full the new keys are evicted at once and every task
misses: 98 us per task at 64 threads, measured.) The hit test still
compares the scope (===), and a collision of two different unions only
replaces the entry. Everything else keeps objectid.
…all of them

estimate_task_costs! shuffled (randperm!) and sorted every candidate processor
for every unscoped task, although the scheduler takes the first usable one:
O(T log T) per task, 12 -> 24-58 us per task at 8 -> 32-64 threads on our cluster
(Opteron). The scheduler-facing path (costs === nothing) now rotates the
candidates by a random offset and selects the 4 cheapest into the front; ties
stay random, the tail keeps rotation order. The path that returns costs keeps
the full sort. The ordering is a plain function with concrete argument types.

Fan-out of 64 tiny unscoped tasks at 64 threads, spawn only, 6 interleaved
rounds in one allocation: median 11.3 -> 10.7 ms (about 6 % faster, better in
6 of 6 rounds).
After every do_tasks, every other processor's doorbell was rung "to make it steal".
Each woken runner then scanned the queues of all T processors, locking each one:
T wake-ups and ~T^2 lock operations per enqueued task. For a task whose scope is an
ExactScope nobody else can take it at all (proc_in_scope is proc == scope.processor),
and for an unscoped task one thief is enough.

* ExactScope tasks only: no kick.
* Otherwise wake at most one runner per enqueued task, chosen among the runners that
  are parked (ProcessorInternalState.parked, set before the runner looks for work and
  cleared when it takes a task: one that is not parked looks at the queues again by
  itself, so skipping it cannot lose a wake-up) and that could take a task (scope,
  acceleration, free occupancy: the same test the steal scan applies). The starting
  point rotates so the same runners are not always the thieves. The MPI rule
  (stealing_permitted) stays.

One process, no MPI, our cluster (Opteron 6272), tasks/s with 50 us bodies, before -> after,
8 / 16 / 32 / 64 threads (single runs, bench shm_scaling.jl):
  unscoped  6.6k / 4.9k / 5.7k / 3.3k -> 6.0k / 5.1k / 6.0k / 5.6k   (64 threads +69 %)
  pinned    7.0k / 7.2k / 8.3k / 5.5k -> 7.5k / 8.0k / 8.8k / 7.2k   (64 threads +32 %)
With 500 us bodies at 64 threads: unscoped 3.7k -> 4.2k, pinned 5.8k -> 7.5k.
Within noise at 8 and 16 threads, as expected: the wasted work grows with T^2. The
throughput no longer falls between 32 and 64 threads but stays at ~6-8k tasks/s: what
remains is the serial per-task cost of the submitting thread (~125-165 us here).

Tests: thunk, scheduler, processors, uniform-placement, scopes, options, task-queues,
task-affinity, mutation pass (-p 2 -t 2).
The previous commit's do_tasks enqueued a batch and then read each spec again
(scope for the all-pinned check, options.acceleration and est_occupancy for
the wake-up decision). From 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, thunk_id to 0), so on few threads with short tasks the scope
assertion threw a TypeError, the wake-up decision used stale values, and
FireTaskSpec reported the failure under first_task.thunk_id, read after the
recycle: id 0, or the id of whatever task had reused the spec, which failed an
innocent bystander.

The decision data (scope, acceleration, occupancy) is now captured in reusable
vectors inside the enqueue loop, while do_tasks still owns the spec, and the
all-pinned check and the kick loop use those; FireTaskSpec reads first_thunk_id
before do_tasks. Skipped (pre-cancelled / already running) tasks no longer
count towards maxkick.

Regression test: AFTER_ENQUEUE_HOOK (one load and compare per batch) lets the
test sleep right after the enqueue; with 2+ threads the batch counter
FIRE_FAILURES must not move. The test fails on the previous commit plus the
hook and passes with the fix.
…s has many candidates

With every candidate a thread of one process, a candidate's cost is its
reserved pressure alone (same-worker transfers are free, the signature's time
estimate is the same for all), yet estimate_task_costs! read every counter,
filled a cost vector and rotated/selected the order: O(threads) work that
phase timers on our cluster put at 9 + 5 + 3.5 us at 4 threads and 26 + 10 + 14 us at
64 threads, of a ~110 / ~155 us task. For more than TWO_CHOICES_MIN (8)
candidates of one worker and no per-candidate cost dict, the scheduler now
samples two candidates, takes the one with less pressure, and keeps the rest in
rotation order as capacity fallbacks. Idle runners steal what is queued behind
a busy one, so the first choice only has to be good, not optimal.

Multi-worker candidate sets, datadeps (one
candidate) and callers that want the costs are untouched.

Laptop, 16 threads, plain @Spawn: 36 -> 16 us per task. Balance probe
(sleeping tasks, equal and irregular, 5 rounds, both placements in one
process): makespan ratios within noise of the full ranking. Measurements on our cluster follow.
…cess

schedule_one! ranks candidate processors across workers, re-checks every
candidate against the scope, and takes capacity locks, for tasks whose
candidates are all CPU threads of this process (has_capacity always says
yes, same-worker transfers cost nothing, a ThreadProc accepts every
function and argument type). Such a task now takes the compatible set of
its scope from the cached entry (the set the general path used), picks the
less loaded of two random threads (all of them when there are 8 or fewer)
from pressure counters resolved once per scheduler, and reserves the
counter. Falls back to the general path for proclist/single/time_util/
alloc_util/occupancy, for scopes the scheduler would have to build or
constrain (compute/result scope, chunk scope restrictions), for any
acceleration but DistributedAcceleration (MPI), for a compatible set with
a non-local or non-ThreadProc member (workers, GPUs), and when a thread
refuses the function or an argument type. test/local-fastpath.jl covers the fast and the fallback
cases and that the pressure is released.
The compatible-set cache is one frequency-ordered cache behind one lock and
a hit updates the frequency under it, so every placing thread took that lock
for every task: the candidate lookup of a fast-path task measured 3.9 us at
16 threads and 11.7 us at 64 (flat Datadeps Cholesky: 9.7 / 28.6 us). The
fast path now keeps the same CompatEntry objects in a dictionary that is
replaced, not mutated, when an entry is added (bounded to 2048 keys, emptied
with the cache when the processor hierarchy changes), so a lookup takes no
lock.
…snapshot

compatible_processors_ordered went through the frequency cache behind one lock
(every placing thread, every task: 12-29 us per task at 64 threads on our
cluster, per the fast path's measurements); it now uses the snapshot of the
local fast path (same entries, same canonical order, a miss falls through to
compat_entry). Laptop, 4 threads, plain @Spawn under MPI with one rank:
15.32 -> 14.2 us per task. Local suites: thunk, processors, uniform-placement
(5780), two-choices (9506), local-fastpath, options, task-queues; MPI 2 ranks x
2 threads suite.
Each decision of the fast path is now asserted directly: which compatible sets
qualify (this process's threads only, the distributed acceleration only), that the
path places tasks (its counters get built), that a scope restriction on a chunk
argument and unscoped tasks with workers are not decided by it, that
pick_fast_candidate takes the less loaded of two threads above TWO_CHOICES_MIN and
the least loaded at or below it, that estimate_task_costs! switches to two choices
only above the limit, and that the lock-free snapshot is bounded and emptied with
the compatible-set cache.
Review finding 4 on PR JuliaParallel#814 (blocker): New placement tests fail with DistributedNext in CI
Requested: Use the test harness's selected Distributed transport in both new placement tests.

Import the module already bound by runtests.jl. The original two-choices
test reproduced the Distributed binding error locally. With the relative
imports and DistributedNext selected, Two-choices Placement passed
9,503 assertions and Local Fast Path passed 729.

Written by an AI agent on jpsamaroo's review feedback.
Review finding 1 on PR JuliaParallel#814 (blocker): The fast path can choose a thread rejected by a compatibility hook
Requested: Check compatibility with the chosen processor before reserving it, and use the general scheduler if that candidate is rejected.

Check both function and argument compatibility against the actual choice.
An incompatible candidate leaves pressure and reservations untouched. The
two targeted refusal cases and their accounting assertions pass. Julia
1.12.6 with DistributedNext passes Two-choices Placement 9,503/9,503 and
Local Fast Path 733/733 on the combined fixes.

Written by an AI agent on jpsamaroo's review feedback.
Review finding 2 on PR JuliaParallel#814 (blocker): Local placement can race updates to the worker channel table
Requested: Use the initialized-worker processor snapshot from phase 1 in the fast candidate lookup and remove the unlocked worker channel lookup.

The general scheduler already consumes the registered worker snapshot
created under the state lock. Reuse it for the local candidate cache so
phase 2 never reads the mutable worker-channel dictionary.

Two-choices Placement passed 9,503/9,503 and Local Fast Path 733/733
with DistributedNext. Minimum among six warm samples for 250 spawns
during A/B for the combined fix was 41,343 to 40,202 allocations and
1,323,392 to 1,285,104 bytes on Julia 1.12.6 with two threads.

Written by an AI agent on jpsamaroo's review feedback.
@codecov

codecov Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.72131% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 64.84%. Comparing base (46f6315) to head (27d7c62).

Files with missing lines Patch % Lines
src/sch/Sch.jl 94.32% 8 Missing ⚠️
src/sch/fastpath.jl 97.03% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #814      +/-   ##
==========================================
+ Coverage   64.35%   64.84%   +0.49%     
==========================================
  Files         126      127       +1     
  Lines       20191    20474     +283     
==========================================
+ Hits        12993    13276     +283     
  Misses       7198     7198              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Retain the local placement path while bringing in current scheduler diagnostics and dependency fixes.

Written by an AI agent on jpsamaroo's review feedback.
Review finding F3 (should-fix) on PR JuliaParallel#806: Mixed-scope batches can scan every runner and task combination.

Skip pinned task metadata and use broad wakeups if the runner/task cross product exceeds 64 eligibility checks. Read runner occupancy under its queue lock on the selective path. This retains selective wakeups for small batches while bounding filtering work by the batch plus runner counts.

Written by an AI agent on jpsamaroo's review feedback.
Review finding F1 (should-fix) on PR JuliaParallel#806: Placement beyond the fourth candidate no longer follows cost order.

State which candidates are cost-ranked and which retain rotation order; the existing partial-ranking tests cover the implemented ordering.

Written by an AI agent on jpsamaroo's review feedback.
Review finding F2 (should-fix) on PR JuliaParallel#814: The fast index can republish stale processor sets after invalidation.

Associate each compatible entry with the processor hierarchy generation. Retry computations invalidated before either cache publication, and check the generation on fast cache hits. Invalidation increments the token while clearing the main cache.

Also strengthen the refused-argument regression so the kernel itself would accept the argument and only a scheduling refusal satisfies the assertion.

Written by an AI agent on jpsamaroo's review feedback.
Review finding F3 (should-fix) on PR JuliaParallel#814: A cache miss can copy the whole index once per placement.

Replace the copy-on-write dictionary with 2048 stable direct-mapped slots. Hits check the full key, scope, processor list and generation; collisions replace one slot. Add a forced scope-collision regression and preserve bounded/invalidation coverage. Store local CPU candidates in a concrete ThreadProc vector while constructing those entries.

Written by an AI agent on jpsamaroo's review feedback.
Review finding F6 (should-fix) on PR JuliaParallel#814, shared with PR JuliaParallel#806: Rotating candidates skews choices among tied minima.

Use reservoir sampling within each selection pass. A minimum no longer wins in proportion to the distance from the previous minimum. The regression places two minima behind unequal gaps and checks their first-choice counts.

Written by an AI agent on jpsamaroo's review feedback.
Review finding F14 (should-fix) on PR JuliaParallel#814: The scheduler manual omits approximate candidate selection.

Document the four-candidate general ranking, local pressure ranking, two-choice sampling and transfer-rate policy difference, with the conditions that select the general path.

Written by an AI agent on jpsamaroo's review feedback.
Independent review on PR JuliaParallel#814: The two-choice shortcut also accepted GPUs or mixed processor types sharing one worker, discarding their distinct transfer and memory-space costs.

Require a homogeneous ThreadProc candidate set before compute-pressure-only ranking. Add same-worker virtual device and mixed-candidate eligibility regressions. Update the remaining test snapshot helper to read the new atomic slots.

Written by an AI agent on jpsamaroo's review feedback.
Independent review of PR JuliaParallel#814 requested direct coverage of fast cache generation checks as well as the blocked-computation invalidation regression. Seed an otherwise matching slot with an old generation and verify lookup rejects it.

Written by an AI agent on jpsamaroo's review feedback.
Follow-up on the bounded wakeup scan in PR JuliaParallel#806: A fixed 64-probe cap would wake every runner for a single task on a pool larger than64, restoring the scalability cliff this PR removes.

Bound filtering by eight times the combined runner and task counts instead. Singleton batches retain a linear selective scan; large cross-products still fall back to broad waking.

Written by an AI agent on jpsamaroo's review feedback.
jpsamaroo added a commit to AnnaLena77/Dagger_AL.jl that referenced this pull request Nov 30, 2026
Review finding F6 (should-fix) on PR JuliaParallel#814, shared with PR JuliaParallel#806: Rotating candidates skews choices among tied minima.

Use reservoir sampling within each selection pass. A minimum no longer wins in proportion to the distance from the previous minimum. The regression places two minima behind unequal gaps and checks their first-choice counts.

Written by an AI agent on jpsamaroo's review feedback.
The strengthened argument-refusal test on PR JuliaParallel#814 correctly observed SchedulingException, but compared its full reason against only a prefix. Use the test helper's prefix assertion so task IDs and scope diagnostics remain visible. The failing run otherwise passed725 placement assertions, including the invalidation race and cache collision regressions.

Validation: local fast-path suite726 passes; two-choices suite9507 passes. The isolated1024-miss fast-index profile after10warmups and GC, minimum3 runs, falls from11079 allocations /53450128 bytes to4609 allocations /204816 bytes (all samples identical).

Written by an AI agent on jpsamaroo's review feedback.
Review finding F11 (should-fix) on PR JuliaParallel#814: Fast and general placement duplicate cost and reservation bookkeeping.

Use has_capacity with absent resource overrides for the fast path, specializing away the branches it never needs. Both paths now reserve through reserve_pressure!, which captures the exact counter and estimate used by completion. Keep the fast path's cached counter lookup. Existing placement tests verify pressure is fully released on both normal and fallback paths.

Written by an AI agent on jpsamaroo's review feedback.
Independent review of PR JuliaParallel#814 found that the shared JuliaParallel#806 scope optimization scans every cached scope on each new worker/device processor miss.

Stop after16 entries. Scope sharing remains an optional identity reuse optimization; missing a later match does not alter eligible processors. A counted1024-entry cache regression verifies a bounded miss and immediate reuse of an early match.

Written by an AI agent on jpsamaroo's review feedback.
Review finding F2 on PR JuliaParallel#814: Clearing both caches does not prevent in-flight computations from republishing old compatible processor sets. Document the generation and deterministic paused-computation test pattern.

Written by an AI agent on jpsamaroo's review feedback.
The full scheduler check exposed a merge-resolution mistake in PR JuliaParallel#814: the new fallback rendered the scope directly, bypassing master's safe metadata formatter and allowing a user show method to throw.

Use scheduling_scope_name and report the initialized processor count exactly as master does. The existing diagnostic regression checks a large captured function, a throwing callable/scope show method, and short ExactScope metadata.

Written by an AI agent on jpsamaroo's review feedback.
Complete the scheduler policy documentation for PR JuliaParallel#814: the general path can sample two same-worker CPU threads even when the worker is remote. Explain that cross-worker and device candidates retain the transfer-aware path.

Validation: the shared estimates/reservation profile over 10,000 warmed iterations allocates 0 objects / 0 bytes both before and after (10 warmup groups, GC, minimum of three identical runs). The final focused diagnostic and scope-sharing checks pass 9 and 4 assertions respectively.

Written by an AI agent on jpsamaroo's review feedback.
jpsamaroo added a commit to AnnaLena77/Dagger_AL.jl that referenced this pull request Nov 30, 2026
Independent review of PR JuliaParallel#814 found that the shared JuliaParallel#806 scope optimization scans every cached scope on each new worker/device processor miss.

Stop after16 entries. Scope sharing remains an optional identity reuse optimization; missing a later match does not alter eligible processors. A counted1024-entry cache regression verifies a bounded miss and immediate reuse of an early match.

Validation: the counted miss reproduces 1,024 visits before versus 17 fetched entries (16 comparisons) afterwards. Both scope-sharing variants allocate 0 bytes across 1,000 warmed calls (minimum of three runs).

Written by an AI agent on jpsamaroo's review feedback.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants