diff --git a/AGENTS.md b/AGENTS.md index ad8c5740e..a85eb6807 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1217,3 +1217,121 @@ 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. + +109. **Thread 1 is not always a Dagger thread.** Julia numbers interactive + threads first and, since 1.12, starts one by default (`-t N` means N + default threads plus one interactive; `-t N,1` does the same on 1.10 and + 1.11). Thread 1 is then interactive, the main task and REPL run on it, and + the default pool is threads `2:N+1`. `Threads.nthreads()` counts only the + default pool, so `1:nthreads()` is the wrong set: registering ThreadProcs + for it ran Dagger tasks on the interactive thread and never on the last + default thread. ThreadProcs come from `default_pool_tids()`; where code + means "the first thread", use `first_default_tid()` (or, for another + worker, its lowest-tid ThreadProc), never a literal `1`. A scope naming a + thread with no processor (`ExactScope(ThreadProc(1, 1))`) fails to + schedule rather than falling back, so a stray literal breaks only on + configurations with an interactive thread. In CI those are the 1.12+ + multithreaded jobs (`-t auto`) and MPI ranks (`--threads=2`), not 1.10/1.11 + or the distributed job (`JULIA_NUM_THREADS=1`); the processors suite runs a + `-t 2,1` subprocess so every version covers it. + +110. **Start Distributed test workers before the first eager Dagger task.** + `eager_context()` takes its worker list from `procs()` when it is first + created. A local warmup or a processor probe that spawns a task can + initialize it before the test calls `addprocs`. The workers will + then appear in Distributed's list while exact Dagger scopes naming them + fail to schedule. Launch and load Dagger on the workers first, or use + `Dagger.addprocs!(ctx, workers)` to extend an existing context. + +111. **Mutable metadata changes immutable scope identity.** Adding a `Set` field + to `UnionScope` makes separately constructed scopes unequal under `===`, + even when their retained tuples and `==` results match. The scheduler + keys compatible-processor entries with `objectid(scope)` and checks `===`, + so that change loses reuse across equivalent regions. Keep retained + membership sets in an external bounded cache and put only deterministic + immutable metadata in the scope. Check fresh constructor identity and + compatible-set identity, not just equality. A hot cache key must also avoid + indexing an abstract `Tuple`: that boxes its immutable elements. Retain a + content hash at construction instead, and measure the lookup allocations. + Derived hashes must be rebuilt after serialization because member + identities can change. Do not serialize cached identity hashes as data. + Specializing a function on a large scope tuple also incurs its full tuple + ABI cost: a three-member fingerprint prototype took 18 s to compile at 1024 + members and its lookup scaled with tuple size despite zero allocations. + +112. **An elided result's failure protocol belongs to its handles.** A live + optimization flag cannot decide whether an existing MPI result checks for + poison: disabling elision after submission otherwise strands nonowners and + desynchronizes later generic fetch tags. Capture the protocol at root + submission, retain its failure state through the DTask and every result + MPIRef, and keep relay registration weak. Failure delivery may precede a + lagging rank's submission; retain only those early messages until ordered + root registration reaches their task id. Generate that id after metadata + hooks finish, so reentrant submission cannot skip a registration gap. + A per-task checkpoint hook makes every rank a participant, even when its + result is only metadata there. Reject checkpointed tasks after option + defaults are applied; elision must preserve each rank's callback. + Captured failure-only mode also precedes inference-based broadcast planning: + an explicitly declared result can infer as `Union{}` when it always throws, + but elided ranks still cannot consume an ordinary metadata/error FIFO slot. + Skipping task ids advances that same registration watermark: discard early + failure notifications for skipped ids, and reject late ones, because no + result handle will ever consume them. Keep weak states for live handles. + +113. **An MPI source may reach a later argument before its receiver.** Moves + are ordered within each rank, not across ranks: a spectator of argument 1 + can already post argument 2's rendezvous send while the owner still waits + for argument 1. If argument 1 fails, the owner never receives argument 2; + MPI.Cancel does not guarantee that unmatched send will complete. Failure-only + owner elision therefore waits for receiver readiness before posting each + cross-rank argument. Route readiness through the independent metadata relay, + and make readiness waits poisonable, so no data request depends on a peer + that already abandoned the task. Preserve live request buffers until MPI + completes or cancels their transfer when an active wait throws. + +114. **Async payloads can permanently pin a reusable task.** A cache setup + callback runs only when its slot is created. A later payload that schedules + `@async` makes that Task sticky, so a pool advertised as migratable can + silently accumulate pinned slots. Retire a formerly migratable slot that + becomes sticky; do not unset sticky while its children may still rely on + the affinity. Close its channel before publishing readiness, and replace + closed slots on dispatch, so a new payload cannot be lost during retirement. + +115. **Free-thread execution still needs processor compatibility.** A broad + MPI scope does not imply that an extension's `iscompatible_func` or + `iscompatible_arg` accepts every CPU thread. Before making a task + migratable, check those predicates across its rank's CPU candidates with + the scheduler's function/argument types. Otherwise a logically compatible + selected processor can execute on an incompatible physical thread. Test + restrictive hooks while their sole eligible thread is busy. + +116. **Stolen Python work still needs Python's GIL.** The CPU work stealer's + broad compatibility predicate can select a Python callable even though + direct placement prefers `PythonProcessor`. Registering only default-pool + CPU threads exposes this when the GIL belongs to interactive thread 1. + Delegate typed `ThreadProc`/`Py` execution to the GIL-safe Python executor, + retaining CPU profiling and exception handling. Use a private result per + offloaded call: PythonCall's shared reply channel can mix concurrent or + cancelled callers, and its error printer runs on the receiving thread + without the GIL. Remember the interpreter's actual initialization thread + rather than assuming thread 1. A one-shot task there can return the original + captured exception as a value, without formatting it there. A successful + direct-placement test does not exercise the stealing dispatch. Do not give + the offloaded task pooled Dagger TLS: cancellation can recycle that metadata + while Python is still finishing. Copy only the logging flag and scalar ID. + + +117. **A docstring link needs a rendered binding, including its own links.** Documenter cannot resolve a function `@ref` merely because that function has a source docstring. Include its binding in an API `@docs` block, and follow the referenced docstring's links too: documenting `skip_tasks!` requires both `elide_foreign_tasks!` and its linked `elide_task!` hook. A source-only name check is not a complete documentation build. + +118. **Assert free-thread progress inside the kernel, before result delivery.** + Timing `fetch` in an MPI scheduling test includes result metadata and + broadcast progress after the kernel has run. Keep an explicitly pinned + thread occupied behind a rank-local atomic gate and record whether a + broad-scope kernel runs before release. Waiters must sleep, release the + gate in `finally`, and give the non-yielding busy kernel a bounded escape + deadline. Record wait statuses while occupied, then report assertions only + after release. In the forced-bound control, reporting an assertion before + `finally` deferred release past the busy kernel's watchdog. Fetch every + busy task before resetting shared test state. An + exact-scope negative control must run only after release. This distinguishes + execution progress from delivery latency without relaxing a speed bound. diff --git a/docs/src/api-dagger/functions.md b/docs/src/api-dagger/functions.md index 298734514..7a78c78da 100644 --- a/docs/src/api-dagger/functions.md +++ b/docs/src/api-dagger/functions.md @@ -86,3 +86,11 @@ Sch.exec! Sch.halt! Sch.get_dag_ids ``` + +## MPI Submission Control + +```@docs +elide_foreign_tasks! +elide_task! +skip_tasks! +``` diff --git a/docs/src/darray.md b/docs/src/darray.md index 76d909290..566765f69 100644 --- a/docs/src/darray.md +++ b/docs/src/darray.md @@ -244,12 +244,13 @@ The `assignment` argument accepts the following values: * `AbstractArray{<:Int, N}`: * Provide an integer **N**-dimensional array of worker IDs. The dimension **N** must match the number of dimensions of the `DArray`. - * Dagger maps blocks to worker IDs in a block-cyclic manner according to this processor-array. The block at index `(i,j,...)` is assigned to the first CPU thread of the worker with ID `assignment[mod1(i, size(assignment,1)), mod1(j, size(assignment,2)), ...]`. This pattern repeats block-cyclically across all dimensions. + * The block at index `(i,j,...)` is assigned to the first default-pool CPU thread of the worker with ID `assignment[mod1(i, size(assignment,1)), mod1(j, size(assignment,2)), ...]`. This pattern repeats block-cyclically across all dimensions. * `AbstractArray{<:Processor, N}`: * Provide an **N**-dimensional array of `Processor` objects. The dimension **N** must match the number of dimensions of the `DArray` blocks. * Blocks are mapped in a block-cyclic manner according to the `Processor` objects in the assignment array. The block at index `(i,j,...)` is assigned to the processor at `assignment[mod1(i, size(assignment,1)), mod1(j, size(assignment,2)), ...]`. This pattern repeats block-cyclically across all dimensions. + * Each explicit `ThreadProc(worker, tid)` must name a registered default-pool thread on that worker. If existing code uses `ThreadProc(worker, 1)` to mean the first CPU thread, use an integer worker assignment or look up its registered CPU processors as shown below. #### Examples and Usage @@ -265,7 +266,10 @@ The `assignment` argument works similarly for `DArray`, `DVector`, and `DMatrix` * `rand`, `randn`, `sprand`, `ones`, `zeros`: Functions to create DArrays with initial values, also supporting `assignment`. -Here are some examples using a setup with one master process and three worker processes. +Here are some examples using one master process and three worker processes. The +sample outputs show a configuration without interactive threads. Julia assigns +interactive thread IDs first when that pool is enabled, so the default-pool IDs +can differ across workers. First, let's create some sample arrays for `distribute` (and constructor functions): @@ -419,7 +423,7 @@ M = zeros(5, 5, 5) # 3D array # distribute(sprand(7,11, 0.2), Blocks(2, 2), assignment_2d) ``` - The assignment is an integer matrix of worker IDs, the blocks are assigned in block-cyclic manner to the first CPU thread of each worker. The assignment for `Ad` (and `Rd`) would be: + The assignment is an integer matrix of worker IDs. Blocks are assigned in a block-cyclic manner to the first default-pool CPU thread of each worker. The assignment for `Ad` (and `Rd`) would be: ```julia 4×6 Matrix{Dagger.ThreadProc}: @@ -431,21 +435,26 @@ M = zeros(5, 5, 5) # 3D array 4. **Block-Cyclic Assignment with Processor Array:** + This example assumes at least three default-pool threads on each process. + ```julia - assignment_2d = [Dagger.ThreadProc(3, 2) Dagger.ThreadProc(1, 1); - Dagger.ThreadProc(4, 3) Dagger.ThreadProc(2, 2)] + cpu_procs(worker) = sort!([p for p in Dagger.get_processors(Dagger.OSProc(worker)) + if p isa Dagger.ThreadProc]; by=p -> p.tid) + cpus1, cpus2, cpus3, cpus4 = cpu_procs.(1:4) + + assignment_2d = [cpus3[2] cpus1[1]; cpus4[3] cpus2[2]] Ad = distribute(A, Blocks(2, 2), assignment_2d) # DMatrix(A, Blocks(2, 2), assignment_2d) - assignment_1d = [Dagger.ThreadProc(2,1), Dagger.ThreadProc(3,1), Dagger.ThreadProc(1,1), Dagger.ThreadProc(4,1)] + assignment_1d = [cpus2[1], cpus3[1], cpus1[1], cpus4[1]] vd = distribute(v, Blocks(3), assignment_1d) # DVector(v, Blocks(3), assignment_1d) - assignment_3d = cat([Dagger.ThreadProc(1,1) Dagger.ThreadProc(2,1); Dagger.ThreadProc(3,1) Dagger.ThreadProc(4,1)], - [Dagger.ThreadProc(4,1) Dagger.ThreadProc(3,1); Dagger.ThreadProc(2,1) Dagger.ThreadProc(1,1)], dims=3) + assignment_3d = cat([cpus1[1] cpus2[1]; cpus3[1] cpus4[1]], + [cpus4[1] cpus3[1]; cpus2[1] cpus1[1]], dims=3) Md = distribute(M, Blocks(2, 2, 2), assignment_3d) # DArray(M, Blocks(2, 2, 2), assignment_3d) - Rd = rand(Blocks(2, 2), 7, 11; assignment=assignment_2d)) + Rd = rand(Blocks(2, 2), 7, 11; assignment=assignment_2d) # distribute(rand(7,11), Blocks(2, 2), assignment_2d) ``` diff --git a/docs/src/mpi.md b/docs/src/mpi.md index a28e124e1..9eb671ebe 100644 --- a/docs/src/mpi.md +++ b/docs/src/mpi.md @@ -199,6 +199,19 @@ with rank information: - `MPIMemorySpace` — a rank-stamped [memory space](data-management.md) (CPU RAM, or device VRAM) used to track where data resides. +An MPI CPU task whose scope permits every default-pool thread of its rank can +run on any free default-pool thread when its function and arguments are also +compatible with every CPU thread. A scope or extension compatibility predicate +that excludes any of those threads keeps the task on the scheduler's selected +thread. `Dagger.task_processor()` +reports the MPI processor for the thread executing that query; a migratable task +can observe a different thread after yielding. Interactive threads remain outside +the CPU processor pool. + +MPI activation leaves process allocator settings unchanged. Applications that +want glibc to retain freed tile buffers can explicitly call `Dagger.tune_malloc!()`; +the setting applies to the whole process and persists after MPI deactivation. + You can enumerate the processors of the cluster (useful for building scopes): ```julia @@ -346,6 +359,68 @@ hooks — `Dagger.mpi_device_direct`, `Dagger.mpi_device_sync`, `Dagger.mpi_library_gpu_aware`, and `Dagger.mpi_remap_space` — are overridable per backend for advanced setups. +## Skipping tasks a rank takes no part in (owner elision) + +Under SPMD every rank plans every task, including tasks it neither runs nor owns +data for. `Dagger.elide_foreign_tasks!(true)` lets such a rank skip the thunk, +scheduling and placeholder execution of a task (it only takes the task id, so ids +and tags stay equal on every rank). It is off by default, and every rank must set +it to the same value at the same point of the program; changing it waits for the +tasks already submitted. + +A CPU task is eligible when its result type proves host storage, its owner is +known at submission, it has no explicit tag, and this rank owns none of its +arguments. A rank scope supplies the owner; an unscoped task can use deterministic +placement at submission. Placement uses the scheduler's registered processors, +option defaults, and function/argument compatibility checks. GPU processors and +custom result types retain the normal metadata exchange. A rank-wide CPU scope +still permits execution on a free thread of that rank. + +Elision applies to root-task submissions through the ordinary queue and +`spawn_bulk`. Tasks inside Datadeps regions and inside other tasks are never +elided, and neither are tasks of another communicator or tasks submitted while +`check_uniformity!(true)` is on. + +The consequence to be aware of: the owner of an elided task reports only +failures. A rank that never fetches the task or consumes its result does not wait +for it and does not notice that it finished or failed; a rank that does consume +it sees the owner's error. +The task and its result handles retain that failure for repeated fetches, including +after elision is disabled. Failure state is released when its last handle dies. + +### Omitting foreign submissions + +For a task that this rank would elide, `Dagger.skip_tasks!(n)` can replace `n` +consecutive submissions entirely. All ranks must agree on the same task positions; +each position is either submitted or skipped on every rank. For example, run this +at the root task on every rank: + +```julia +Dagger.check_uniformity!(false) +Dagger.elide_foreign_tasks!(true) +for k in 1:7 + if MPI.Comm_rank(MPI.COMM_WORLD) == 0 + Dagger.@spawn scope=Dagger.scope(mpi_rank=0) return_type=Int identity(k) + else + Dagger.skip_tasks!(1) + end +end +Dagger.elide_foreign_tasks!(false) # Wait for this phase before changing modes. +Dagger.check_uniformity!(true) +``` + +A skipped task must have a concrete host result type and a known CPU owner, no +explicit tag, and no argument data owned by the skipping rank. Its result must +never be fetched or used on that rank: skipping creates no placeholder, and +failure notifications for skipped ids are discarded. Callbacks, dependencies, +and other options that require the rank to participate make skipping invalid. +These task eligibility conditions are the caller's responsibility. + +Positive counts require enabled elision, disabled collective uniformity checks, +the world communicator, and an ordered root-task call. Counts must fit the +remaining MPI tag range. Invalid calls leave task ids and eager initialization +unchanged; zero does nothing. Other accelerations treat skipping as a no-op. + ## Collecting and fetching results `collect(DA)` performs a deterministic, rank-uniform gather: it returns the full diff --git a/docs/src/task-affinity.md b/docs/src/task-affinity.md index 53303923e..53aacd731 100644 --- a/docs/src/task-affinity.md +++ b/docs/src/task-affinity.md @@ -4,6 +4,21 @@ Dagger's allows for precise control over task placement and result availability For more information on how scopes work, see [Scopes](@ref). +CPU scopes use the selected worker's Julia thread IDs. Dagger registers only +default-pool threads as CPU processors. If Julia gives thread 1 to the +interactive pool, a scope limited to that thread has no eligible CPU processor. +To migrate `thread=1` code that meant the first compute thread, use the first +registered CPU thread ID on the target worker. + +The examples below assume processes 1 through 4 each have at least four default +threads. Look up their IDs once before constructing the scopes. + +```julia +cpu_tids(worker) = sort!([p.tid for p in Dagger.get_processors(Dagger.OSProc(worker)) + if p isa Dagger.ThreadProc]) +tids1, tids2, tids3, tids4 = cpu_tids.(1:4) +``` + --- ## Task Scopes @@ -26,10 +41,11 @@ Like `scope`, `compute_scope` also specifies where a Dagger task can execute. Th **Example:** ```julia -g1 = Dagger.@spawn scope=Dagger.scope(worker=2,thread=3) compute_scope=Dagger.scope((worker=1, thread=2), (worker=3, thread=1)) f(x,y) -g2 = Dagger.@spawn compute_scope=Dagger.scope((worker=1, thread=2), (worker=3, thread=1)) f(x,y) +compute_scope = Dagger.scope((worker=1, thread=tids1[2]), (worker=3, thread=tids3[1])) +g1 = Dagger.@spawn scope=Dagger.scope(worker=2, thread=tids2[3]) compute_scope=compute_scope f(x,y) +g2 = Dagger.@spawn compute_scope=compute_scope f(x,y) ``` -Tasks `g1` and `g2` execute on either thread 2 of worker 1, or thread 1 of worker 3. The `scope` argument to `g1` is ignored. Their result can be accessed by any worker. +Tasks `g1` and `g2` execute on either the second default thread of worker 1 or the first default thread of worker 3. The `scope` argument to `g1` is ignored. Their result can be accessed by any worker. --- @@ -39,9 +55,9 @@ The result_scope limits the processors from which a task's result can be accesse **Example:** ```julia -g = Dagger.@spawn result_scope=Dagger.scope(worker=3, threads=[1, 3, 4]) f(x,y) +g = Dagger.@spawn result_scope=Dagger.scope(worker=3, threads=tids3[[1, 3, 4]]) f(x,y) ``` -The result of `g` is accessible only from threads 1, 3 and 4 of worker process 3. The task's execution may happen anywhere on threads 1, 3 and 4 of worker 3. +The result of `g` is accessible only from the first, third, and fourth default threads of worker 3. The task may execute on any of those threads. --- @@ -51,9 +67,10 @@ When `scope`/`compute_scope` and `result_scope` are specified, the scheduler exe **Example:** ```julia -g = Dagger.@spawn scope=Dagger.scope(worker=3,thread=2) compute_scope=Dagger.scope(worker=2) result_scope=Dagger.scope((worker=2, thread=2), (worker=4, thread=2)) f(x,y) +result_scope = Dagger.scope((worker=2, thread=tids2[2]), (worker=4, thread=tids4[2])) +g = Dagger.@spawn scope=Dagger.scope(worker=3, thread=tids3[2]) compute_scope=Dagger.scope(worker=2) result_scope=result_scope f(x,y) ``` -The task `g` computes on thread 2 of worker 2 (as it's the intersection of compute and result scopes), but accessng its result is restricted to thread 2 of worker 2 and thread 2 of worker 4. +The task `g` computes on the second default thread of worker 2, the intersection of the compute and result scopes. The second default threads of workers 2 and 4 can access its result. --- @@ -76,10 +93,11 @@ chunk_proc = Dagger.OSProc(3) # not important, just needs to be a valid processo g(x, y) = x * 2 + y * 3 g_chunk = Dagger.tochunk(g, chunk_proc, chunk_scope) h1 = Dagger.@spawn scope=Dagger.scope(worker=3) g_chunk(10, 11) -h2 = Dagger.@spawn compute_scope=Dagger.scope((worker=1, thread=2), (worker=3, thread=1)) g_chunk(20, 21) -h3 = Dagger.@spawn scope=Dagger.scope(worker=2,thread=3) compute_scope=Dagger.scope((worker=1, thread=2), (worker=3, thread=1)) g_chunk(30, 31) +compute_scope = Dagger.scope((worker=1, thread=tids1[2]), (worker=3, thread=tids3[1])) +h2 = Dagger.@spawn compute_scope=compute_scope g_chunk(20, 21) +h3 = Dagger.@spawn scope=Dagger.scope(worker=2, thread=tids2[3]) compute_scope=compute_scope g_chunk(30, 31) h4 = Dagger.@spawn result_scope=Dagger.scope(worker=3) g_chunk(40, 41) -h5 = Dagger.@spawn scope=Dagger.scope(worker=3,thread=2) compute_scope=Dagger.scope(worker=3) result_scope=Dagger.scope(worker=3,threads=[2,3]) g_chunk(50, 51) +h5 = Dagger.@spawn scope=Dagger.scope(worker=3, thread=tids3[2]) compute_scope=Dagger.scope(worker=3) result_scope=Dagger.scope(worker=3, threads=tids3[2:3]) g_chunk(50, 51) ``` In all these cases (`h1` through `h5`), the tasks get executed on any processor within `chunk_scope` and its result is accessible only within `chunk_scope`. @@ -105,8 +123,9 @@ Task `h` executes on any worker within the intersection of `scope` and `arg_scop If `arg_scope` and `compute_scope` do not intersect, the scheduler throws an exception. Otherwise, execution happens on the intersection of the effective compute scope (which will be `compute_scope` if provided, otherwise `scope`) and `arg_scope`. ```julia -h1 = Dagger.@spawn compute_scope=Dagger.scope((worker=1, thread=2), (worker=2, thread=1)) g(arg, 11) -h2 = Dagger.@spawn scope=Dagger.scope(worker=2,thread=3) compute_scope=Dagger.scope((worker=1, thread=2), (worker=2, thread=1)) g(arg, 21) +compute_scope = Dagger.scope((worker=1, thread=tids1[2]), (worker=2, thread=tids2[1])) +h1 = Dagger.@spawn compute_scope=compute_scope g(arg, 11) +h2 = Dagger.@spawn scope=Dagger.scope(worker=2, thread=tids2[3]) compute_scope=compute_scope g(arg, 21) ``` Tasks `h1` and `h2` execute on any processor within the intersection of the `compute_scope` and `arg_scope`. `scope` is ignored if `compute_scope` is specified. The result is accessible from any processor. @@ -126,6 +145,7 @@ Task `h` executes on any processor within the intersection of `arg_scope` and `r When `scope`/`compute_scope`, `result_scope`, and `Chunk` argument scopes are all used, the scheduler executes the task on the intersection of `arg_scope`, the effective compute scope (which is `compute_scope` if provided, otherwise `scope`), and `result_scope`. If no intersection exists, the scheduler throws an exception. ```julia -h = Dagger.@spawn scope=Dagger.scope(worker=3,thread=2) compute_scope=Dagger.scope(worker=2) result_scope=Dagger.scope((worker=2, thread=2), (worker=4, thread=2)) g(arg, 31) +result_scope = Dagger.scope((worker=2, thread=tids2[2]), (worker=4, thread=tids4[2])) +h = Dagger.@spawn scope=Dagger.scope(worker=3, thread=tids3[2]) compute_scope=Dagger.scope(worker=2) result_scope=result_scope g(arg, 31) ``` -Task `h` computes on thread 2 of worker 2 (as it's the intersection of `arg_scope`, `compute_scope`, and `result_scope`), and its result access is restricted to thread 2 of worker 2 or thread 2 of worker 4. +Task `h` computes on the second default thread of worker 2, the intersection of `arg_scope`, `compute_scope`, and `result_scope`. The second default threads of workers 2 and 4 can access its result. diff --git a/ext/MPIExt.jl b/ext/MPIExt.jl index f867b1cc5..44f29a1ea 100644 --- a/ext/MPIExt.jl +++ b/ext/MPIExt.jl @@ -336,12 +336,92 @@ const MPIClusterProcChildren = Dict{MPI.Comm, Set{Processor}}() # processors the current scope admits (see `uniform_mpi_processors`), not just # on the communicator. const MPIUniformProcsCache = Dict{Tuple{MPI.Comm, Dagger.AbstractScope}, Vector{Processor}}() +const MPIThreadScopesCache = Dict{Tuple{MPI.Comm,Int},Vector{Dagger.ExactScope}}() + +struct MPIExactScopeMembers + scopes::Tuple + members::Dict{Dagger.AbstractScope,Nothing} +end +mutable struct MPIExactScopeMembersCache + @atomic table::Dict{UInt,MPIExactScopeMembers} +end +const MPI_EXACT_SCOPE_MEMBERS = MPIExactScopeMembersCache(Dict{UInt,MPIExactScopeMembers}()) +const MPI_EXACT_SCOPE_MEMBERS_LOCK = ReentrantLock() + +# The constructor retains an immutable content hash; collisions are checked +# with the original scope identity. Publish the bounded table whole for +# lock-free reads, without changing UnionScope identity or indexing its Tuple. +# Retain the Set's backing Dict: returning a Union{Nothing,Set} boxes its +# immutable wrapper on the hot path, whereas the Dict is already a reference. +mpi_exact_scope_key(scope::Dagger.UnionScope) = scope.membership_hash +function Dagger.record_union_scope_members!(scope::Dagger.UnionScope, members::Set{Dagger.AbstractScope}) + for inner in members + inner isa Dagger.ExactScope || return nothing + end + record_mpi_exact_scope_members!(scope, members) + return nothing +end +function record_mpi_exact_scope_members!(scope::Dagger.UnionScope, members::Set{Dagger.AbstractScope}) + key = mpi_exact_scope_key(scope) + return lock(MPI_EXACT_SCOPE_MEMBERS_LOCK) do + old = @atomic MPI_EXACT_SCOPE_MEMBERS.table + hit = get(old, key, nothing) + backing = members.dict + if hit !== nothing && length(hit.members) == length(members) + same_members = true + for inner in members + if !haskey(hit.members, inner) + same_members = false + break + end + end + same_members && (backing = hit.members) + end + table = hit === nothing && length(old) >= 256 ? Dict{UInt,MPIExactScopeMembers}() : copy(old) + # Refresh the tuple reference for this constructor. Equivalent tuples + # share immutable identity, but comparing distinct large tuple objects + # recursively on every task would restore a rank-count-dependent cost. + table[key] = MPIExactScopeMembers(scope.scopes, backing) + @atomic MPI_EXACT_SCOPE_MEMBERS.table = table + return backing + end +end +@inline function mpi_exact_scope_members(scope::Dagger.UnionScope) + key = mpi_exact_scope_key(scope) + hit = get((@atomic MPI_EXACT_SCOPE_MEMBERS.table), key, nothing) + hit !== nothing && hit.scopes === scope.scopes && return hit.members + return mpi_exact_scope_members_slow(scope) +end +@noinline function mpi_exact_scope_members_slow(scope::Dagger.UnionScope) + for inner in scope.scopes + inner isa Dagger.ExactScope || return nothing + end + members = Set{Dagger.AbstractScope}(scope.scopes) + return record_mpi_exact_scope_members!(scope, members) +end # Drop every cached uniform listing for `comm`, across all scopes. function invalidate_uniform_cache!(comm::MPI.Comm) for key in collect(keys(MPIUniformProcsCache)) key[1] == comm && delete!(MPIUniformProcsCache, key) end + for key in collect(keys(MPIThreadScopesCache)) + key[1] == comm && delete!(MPIThreadScopesCache, key) + end + lock(MPI_EXACT_SCOPE_MEMBERS_LOCK) do + old = @atomic MPI_EXACT_SCOPE_MEMBERS.table + table = copy(old) + for (key, entry) in old + for inner in entry.scopes + proc = inner.processor + if proc isa MPIProcessor && proc.comm == comm + delete!(table, key) + break + end + end + end + @atomic MPI_EXACT_SCOPE_MEMBERS.table = table + end end struct MPIClusterProc <: Processor @@ -767,13 +847,154 @@ to_tag(id::MPIRefID) = id.generic ? id.id : id.tid # tochunk sequence within a thunk), so the resulting MPIRefIDs are uniform. const _MPIREF_TID = LockedObject(Dict{Int,Int}()) +# Only handles and in-flight tasks own failure state. The relay's registry is +# weak, so a failed task's exception dies with its last result/task handle. +mutable struct OwnerElisionState + tid::UInt32 + owner::Int + @atomic error::Any + requested_scope::Any + pinned_scope::Any + ready::Int + ready_cond::Union{Threads.Condition,Nothing} +end +OwnerElisionState(tid, owner, err) = OwnerElisionState(tid, owner, err, nothing, nothing, 0, nothing) +struct OwnerFailure + error::Any +end +struct OwnerMoveReady end +mutable struct OwnerEarlyState + error::Any + ready::Int +end +const OWNER_ELISION_STATES = Dict{UInt32,WeakRef}() +const OWNER_ELISION_WAITING = Dict{UInt32,OwnerElisionState}() +const OWNER_ELISION_DIRTY = Threads.Atomic{Bool}(false) +const OWNER_ELISION_LOCK = ReentrantLock() +const OWNER_ELISION_REGISTERED = Ref{UInt}(0) +# A fast owner can notify a rank before its root submits the same task. +const OWNER_ELISION_EARLY = Dict{UInt32,OwnerEarlyState}() +owner_elision_released!(::OwnerElisionState) = (OWNER_ELISION_DIRTY[] = true; nothing) + +# Called with OWNER_ELISION_LOCK held. A shared finalizer marks dead weak +# entries; prune once per GC rather than scanning live tasks per argument. +function owner_elision_register!(state::OwnerElisionState) + if Threads.atomic_xchg!(OWNER_ELISION_DIRTY, false) + for (tid, ref) in OWNER_ELISION_STATES + ref.value === nothing && delete!(OWNER_ELISION_STATES, tid) + end + end + finalizer(owner_elision_released!, state) + OWNER_ELISION_STATES[state.tid] = WeakRef(state) + return state +end +function owner_elision_lookup(tid::UInt32) + ref = get(OWNER_ELISION_STATES, tid, nothing) + return ref === nothing ? nothing : ref.value::Union{OwnerElisionState,Nothing} +end +function owner_elision_deliver!(root::Int, tag::UInt32, err) + @lock OWNER_ELISION_LOCK begin + state = owner_elision_lookup(tag) + if state !== nothing + @atomic state.error = err + state.ready_cond === nothing || notify(state.ready_cond) + end + if UInt(tag) > OWNER_ELISION_REGISTERED[] + early = get!(()->OwnerEarlyState(nothing, 0), OWNER_ELISION_EARLY, tag) + early.error = err + end + end + return +end +function owner_elision_ready!(tag::UInt32) + @lock OWNER_ELISION_LOCK begin + state = owner_elision_lookup(tag) + if state !== nothing + state.ready += 1 + state.ready_cond === nothing || notify(state.ready_cond) + end + if UInt(tag) > OWNER_ELISION_REGISTERED[] + early = get!(()->OwnerEarlyState(nothing, 0), OWNER_ELISION_EARLY, tag) + early.ready += 1 + end + end + note_mpi_progress!() + return +end +function owner_elision_wait_ready!(state::OwnerElisionState) + timer = DeadlockTimer() + @lock OWNER_ELISION_LOCK begin + try + while true + err = @atomic state.error + err === nothing || throw(err) + if state.ready > 0 + state.ready -= 1 + return + end + timer = mpi_deadlock_detect(timer, MPI.Comm_rank(MPI.COMM_WORLD), state.tid, + "owner-elision argument readiness", state.owner) + if state.ready_cond === nothing + state.ready_cond = Threads.Condition(OWNER_ELISION_LOCK) + end + OWNER_ELISION_WAITING[state.tid] = state + wait(state.ready_cond) + end + finally + delete!(OWNER_ELISION_WAITING, state.tid) + end + end +end + +# The relay receives readiness independently of task execution, so this tiny +# control send can finish even if its source task has already failed. Data is +# posted only after the destination reaches this argument; later sources then +# observe poison while waiting, without abandoned rendezvous sends. +function owner_elision_request_argument!(comm::MPI.Comm, source::Int, state::OwnerElisionState) + relay = bcast_state_for(comm) + buf = bcast_serialize((MPI.Comm_rank(comm), OwnerMoveReady())) + req = MPI.Isend(buf, relay.bcast_comm; dest=source, tag=state.tid) + with(POISON_REF => nothing, POISON_TASK => nothing) do + __wait_for_request(req, relay.bcast_comm, MPI.Comm_rank(comm), source, state.tid, + "owner-elision argument readiness", "send") + end + return +end + +function Serialization.serialize(s::Serialization.AbstractSerializer, state::OwnerElisionState) + Serialization.serialize_cycle_header(s, state) && return + Serialization.serialize(s, state.tid) + Serialization.serialize(s, state.owner) + Serialization.serialize(s, @atomic(state.error)) + Serialization.serialize(s, state.requested_scope) + Serialization.serialize(s, state.pinned_scope) +end +function Serialization.deserialize(s::Serialization.AbstractSerializer, ::Type{OwnerElisionState}) + tid = Serialization.deserialize(s)::UInt32 + owner = Serialization.deserialize(s)::Int + state = @lock OWNER_ELISION_LOCK begin + found = owner_elision_lookup(tid) + found === nothing ? owner_elision_register!(OwnerElisionState(tid, owner, nothing)) : found + end + Serialization.deserialize_cycle(s, state) + err = Serialization.deserialize(s) + err === nothing || (@atomic state.error = err) + scope = Serialization.deserialize(s) + state.requested_scope === nothing && (state.requested_scope = scope) + pinned = Serialization.deserialize(s) + state.pinned_scope === nothing && (state.pinned_scope = pinned) + return state +end + mutable struct MPIRef comm::MPI.Comm rank::Int size::Int innerRef::Union{DRef, Nothing} id::MPIRefID + owner_elision::Union{OwnerElisionState,Nothing} end +MPIRef(comm, rank, size, innerRef, id) = MPIRef(comm, rank, size, innerRef, id, nothing) Base.hash(ref::MPIRef, h::UInt=UInt(0)) = hash(ref.rank, hash(ref.id, hash(MPIRef, h))) root_worker_id(ref::MPIRef) = myid() @@ -837,6 +1058,14 @@ function schedule_argument_move(::MPIAcceleration, thunk_id::Integer, f::Functio end return nothing end +function schedule_argument_move(accel::MPIAcceleration, thunk_id::Integer, f::Function, opts::Options, @nospecialize(value)) + state = opts._owner_elision + if !(state isa OwnerElisionState) || !(value isa Chunk) || value isa Chunk{<:Union{Function,Type}} + return schedule_argument_move(accel, thunk_id, f) + end + with(f, DATADEPS_THUNK_ID => Int64(thunk_id), POISON_TASK => state) + return nothing +end # MPI is the only backend that observes SCHED_MOVE inside moves (to suppress # tag creation); the default acceleration performs the move with no scope. @@ -850,8 +1079,9 @@ function take_ref_id!() if Dagger.in_task() tid = sch_handle().thunk_id.id id = next_ref_sub_id!(tid) - elseif DATADEPS_THUNK_ID[] != 0 - tid = DATADEPS_THUNK_ID[] + elseif (dtid = DATADEPS_THUNK_ID[]) != 0 + # One lookup: a scoped value is a walk of the scope chain, and this runs for every task + tid = dtid id = next_ref_sub_id!(tid) else if current_task() !== Base.roottask @@ -868,16 +1098,16 @@ function take_ref_id!() end #TODO: partitioned scheduling with comm bifurcation -function tochunk_pset(x, space::MPIMemorySpace; device=nothing, force_nonlocal=false, kwargs...) +function tochunk_pset(x, space::MPIMemorySpace; device=nothing, force_nonlocal=false, _owner_elision=nothing, kwargs...) @assert space.comm == MPI.COMM_WORLD "$(space.comm) != $(MPI.COMM_WORLD)" local_rank = MPI.Comm_rank(space.comm) Mid = take_ref_id!() if local_rank != space.rank || force_nonlocal - return MPIRef(space.comm, space.rank, 0, nothing, Mid) + return MPIRef(space.comm, space.rank, 0, nothing, Mid, _owner_elision) else # type= is for Chunk metadata only; MemPool.poolset does not accept it pset_kw = (; (k => v for (k, v) in pairs(kwargs) if k !== :type)...) - return MPIRef(space.comm, space.rank, sizeof(x), poolset(x; device, pset_kw...), Mid) + return MPIRef(space.comm, space.rank, sizeof(x), poolset(x; device, pset_kw...), Mid, _owner_elision) end end @@ -1247,19 +1477,34 @@ end function __wait_for_request(req, comm, my_rank, their_rank, tag, fn::String, kind::String) timer = DeadlockTimer() - while true - finish, status = MPI.Test(req, MPI.Status) - if finish - if MPI.Get_error(status) != MPI.SUCCESS - error("$fn failed with error $(MPI.Get_error(status))") + try + while true + finish, status = MPI.Test(req, MPI.Status) + if finish + if MPI.Get_error(status) != MPI.SUCCESS + error("$fn failed with error $(MPI.Get_error(status))") + end + # Every completed request is this rank's proof of life for the + # waits running concurrently with it (see `MPI_PROGRESS`). + note_mpi_progress!() + return end - # Every completed request is this rank's proof of life for the - # waits running concurrently with it (see `MPI_PROGRESS`). - note_mpi_progress!() - return + timer = mpi_deadlock_detect(timer, my_rank, tag, kind, their_rank) + yield() end - timer = mpi_deadlock_detect(timer, my_rank, tag, kind, their_rank) - yield() + catch + # Request_free does not finish the transfer. Its finalizer releases the + # Julia buffer, so retain the request until MPI is done with that buffer. + # An unmatched send can be cancelled; Imrecv has already matched a + # message and must finish receiving it. Cleanup deliberately ignores + # poison and sleeps between polls to let peer tasks make progress. + if !MPI.isnull(req) + kind == "send" && MPI.Cancel!(req) + while !MPI.Test(req) + sleep(0.0001) + end + end + rethrow() end end @@ -1312,6 +1557,13 @@ end # rather than a wait. A real cycle still trips them, just once the work that # does not depend on it has drained. function mpi_deadlock_detect(timer::DeadlockTimer, rank, tag, kind, srcdest) + # A wait on a task's result ends in that task's error when its owner failed + POISON_REF[] === nothing || mpi_check_poison() + task_state = POISON_TASK[] + if task_state !== nothing + err = @atomic task_state.error + err === nothing || throw(err) + end timer.detect || return timer progress = MPI_PROGRESS[] if progress != timer.last_progress @@ -1438,6 +1690,11 @@ function bcast_slot!(state::BcastState, key::Tuple{Int,UInt32}) end function bcast_deliver!(state::BcastState, root::Int, tag::UInt32, value) + if value isa OwnerFailure + owner_elision_deliver!(root, tag, value.error) + note_mpi_progress!() + return + end # `@lock`, not `lock(...) do`: the `do` block is a closure over `state`, # `root`, `tag` and `value`, which boxes them and allocates on a path the # relay runs for every delivered payload. @@ -1464,6 +1721,11 @@ function bcast_heartbeat!(state::BcastState) cond === nothing || notify(cond) end end + @lock OWNER_ELISION_LOCK begin + for waiting in values(OWNER_ELISION_WAITING) + notify(waiting.ready_cond::Threads.Condition) + end + end return end @@ -1540,7 +1802,7 @@ const BCAST_RELAY_HEARTBEAT_ITERS = 1000 # forward the raw bytes to this rank's tree children, then deliver the payload. # Forwarding is NOT gated by datadeps task dispatch — that is what breaks the # forwarder wait-cycle. -function bcast_relay_loop(state::BcastState) +function bcast_relay_loop(state::BcastState, spin_iters::Int=BCAST_RELAY_SPIN_ITERS) comm = state.bcast_comm rank = MPI.Comm_rank(comm) sz = MPI.Comm_size(comm) @@ -1556,7 +1818,7 @@ function bcast_relay_loop(state::BcastState) got, msg, stat = MPI.Improbe(MPI.ANY_SOURCE, MPI.ANY_TAG, comm, MPI.Status) if !got idle += 1 - if idle <= BCAST_RELAY_SPIN_ITERS || !may_backoff + if idle <= spin_iters || !may_backoff yield() else # N.B. `Libc.systemsleep`, not `sleep`: `sleep` parks the @@ -1586,6 +1848,10 @@ function bcast_relay_loop(state::BcastState) req = MPI.Imrecv!(MPI.Buffer(buf), msg) __wait_for_request(req, comm, rank, src, tag, "bcast_relay", "recv") root, value = Serialization.deserialize(IOBuffer(buf)) + if value isa OwnerMoveReady + owner_elision_ready!(tag) + continue + end for child in bcast_tree_children(rank, Int(root), sz) sreq = MPI.Isend(buf, comm; dest=child, tag=tag) __wait_for_request(sreq, comm, rank, child, tag, "bcast_relay", "send") @@ -1608,8 +1874,25 @@ function start_bcast_relay!(accel_comm::MPI.Comm) lock(BCAST_STATES) do states states[accel_comm] = state end - t = Task(() -> bcast_relay_loop(state)) - t.sticky = false + # The relay is a polling loop that keeps a thread busy. From 4 default threads on it is migratable: a + # `Task` made on a thread-bound task (the driver, once Distributed has used `@async`) starts on its + # creator's thread even with `sticky = false`, and a driver parked in a blocking MPI call (an + # `MPI.Allgather` or `Barrier` in user code) would then stop it from forwarding the broadcasts the other + # ranks wait for: a cross-rank cycle that hung the full MPI suite across two nodes. Below 4 threads a + # migratable relay competes with the tasks for the only free thread and hung the delegation test at + # 4 ranks x 2 threads, so there it keeps the creator's thread. + migratable = Threads.nthreads(:default) >= 4 + # A migratable relay that spins on `yield()` wakes another thread with every call (the task goes back to + # the shared queue), which keeps most of a rank's threads out of sleep; it sleeps between probes at once. + # One that stays on the driver's thread shares that thread and must yield to the tasks there. + spin_iters = migratable ? 0 : BCAST_RELAY_SPIN_ITERS + t = Task(() -> bcast_relay_loop(state, spin_iters)) + Dagger.clear_task_scope!(t) + if migratable + Dagger.set_task_migratable!(t) + else + t.sticky = false + end schedule(t) Dagger.Sch.errormonitor_tracked("mpi_bcast_relay", t) state.relay = t @@ -1677,6 +1960,36 @@ function bcast_meta_yield(comm::MPI.Comm, root::Integer, tag, value=nothing) end end +# --- Failure-only task status --------------------------------------------------- +# +# `execute!` of a task that may throw makes the owner broadcast `:ok`/`:error` and +# every other rank wait for it, so every rank is coupled to every task. For the +# tasks `elide_task!` handles (see "Owner elision") the status is instead sent +# *only on failure*: ranks never wait for success, and a rank that later needs the +# task's data -- an argument move or a fetch -- stops waiting when the failure +# arrives. A typed failure notification updates a state shared by the local +# task and its result refs. The relay owns only weak state references, so +# exceptions outlive repeated fetches without accumulating in global slots. +# Waits install the ref they are on behalf of +# in `POISON_REF`, and every polling wait already goes through +# `mpi_deadlock_detect`, which checks it. + +const POISON_REF = ScopedValue{Union{MPIRef,Nothing}}(nothing) +const POISON_TASK = ScopedValue{Union{OwnerElisionState,Nothing}}(nothing) + +function mpi_check_poison() + ref = POISON_REF[]::MPIRef + state = ref.owner_elision + state === nothing && return + err = @atomic state.error + err === nothing || throw(err) + return +end + +# Run `f` (a wait on data of `ref`'s task) so that it ends in that task's error +mpi_poisonable(f, ref::MPIRef) = + ref.owner_elision === nothing ? f() : with(f, POISON_REF => ref) + WeakChunk(c::Chunk{T,H}) where {T,H<:MPIRef} = WeakChunk(c.handle.rank, c.handle.id.id, WeakRef(c), T) function MemPool.poolget(ref::MPIRef; uniform::Bool=uniform_execution()) @@ -1686,7 +1999,9 @@ function MemPool.poolget(ref::MPIRef; uniform::Bool=uniform_execution()) if ref.rank == MPI.Comm_rank(ref.comm) return bcast_yield(ref.comm, ref.rank, tag, poolget(ref.innerRef)) else - return bcast_yield(ref.comm, ref.rank, tag) + return mpi_poisonable(ref) do + bcast_yield(ref.comm, ref.rank, tag) + end end else return poolget(ref.innerRef) @@ -2340,12 +2655,22 @@ function move(src::MPIProcessor, dst::MPIProcessor, x::Chunk) # Source processor for egress uses the chunk's owning rank from = src.rank == x.handle.rank ? src : MPIProcessor(src.innerProc, src.comm, x.handle.rank) + state = POISON_TASK[] + if state !== nothing + if local_rank == x.handle.rank + owner_elision_wait_ready!(state) + elseif local_rank == dst.rank + owner_elision_request_argument!(dst.comm, x.handle.rank, state) + end + end if local_rank == x.handle.rank value = move(from, dst, poolget(x.handle; uniform=false)) send_yield(value, dst.comm, dst.rank, tag) return nothing elseif local_rank == dst.rank - value = recv_yield(dst.comm, x.handle.rank, tag) + value = mpi_poisonable(x.handle) do + recv_yield(dst.comm, x.handle.rank, tag) + end return move(from, dst, value) end return nothing @@ -2464,6 +2789,119 @@ function mpi_execute_bcast_plan(f, args, proc::MPIProcessor) return (; need_type_bcast=false, nothrow, inferred) end +# --- Running a task on a free thread of its rank -------------------------------------- + +function Dagger.task_processor(proc::MPIProcessor{ThreadProc}) + inner = ThreadProc(proc.innerProc.owner, Threads.threadid()) + return MPIProcessor(inner, proc.comm, proc.rank) +end +# +# `execute!(::ThreadProc)` binds the function to the processor's thread, so an MPI task +# waits behind anything that occupies that thread without yielding (a long kernel, a +# rank-local task), whichever thread the scheduler happened to name. A task whose scope +# leaves every thread of its rank open did not ask for a thread: the choice is the +# runtime's and need not be kept, so it runs on whichever eligible thread of its rank is free. +# Custom function/argument compatibility that excludes a CPU thread also pins execution +# to the processor selected by the scheduler. +# A task whose scope excludes some thread of its rank (an `ExactScope`, which is what +# Datadeps and explicit pinning use, or a union of only some threads) did ask for one: +# it stays on the thread of the processor the scheduler picked within that scope. + +function mpi_thread_scopes(proc::MPIProcessor) + key = (proc.comm, proc.rank) + while true + @lock MPI_PROC_CACHE_LOCK begin + haskey(MPIThreadScopesCache, key) && return MPIThreadScopesCache[key] + end + children = ensure_children!(proc.comm) + scopes = Dagger.ExactScope[] + for inner in children + inner isa ThreadProc || continue + push!(scopes, Dagger.ExactScope(MPIProcessor(inner, proc.comm, proc.rank))) + end + @lock MPI_PROC_CACHE_LOCK begin + # A processor callback may have refreshed children while these + # scopes were built outside the registry lock. Retry that snapshot. + if get(MPIClusterProcChildren, proc.comm, nothing) === children + return get!(MPIThreadScopesCache, key, scopes) + end + end + end +end + +# Does `scope` leave out a thread of the rank of `proc`? +function mpi_thread_requested(proc::MPIProcessor, scope) + (scope === nothing || scope isa Dagger.AnyScope || scope === Dagger.DefaultScope()) && return false + thread_scopes = mpi_thread_scopes(proc) + # The scheduler has already established that this processor is eligible. + # On a one-thread rank there is no other CPU thread a scope could exclude. + length(thread_scopes) <= 1 && return false + members = scope isa Dagger.UnionScope ? mpi_exact_scope_members(scope) : nothing + if members !== nothing + for candidate in thread_scopes + haskey(members, candidate) || return true + end + return false + end + return mpi_thread_requested_slow(thread_scopes, scope) +end +function mpi_thread_requested_slow(thread_scopes, scope) + for candidate in thread_scopes + Dagger.proc_in_scope(candidate.processor, scope) || return true + end + return false +end + +# A broad scope does not override extension compatibility constraints. A +# custom function/argument predicate may support only some CPU threads, so +# every physical candidate must be eligible before Julia may migrate the task. +function mpi_task_thread_requested(proc::MPIProcessor, task::Dagger.Sch.TaskSpec, scope=task.scope) + mpi_thread_requested(proc, scope) && return true + options = task.options::Dagger.Options + for scope in mpi_thread_scopes(proc) + candidate = scope.processor::MPIProcessor{ThreadProc} + Dagger.iscompatible_func(candidate, options, task.Tf) || return true + for idx in 2:length(task.data) + Dagger.iscompatible_arg(candidate, options, chunktype(task.data[idx])) || return true + end + end + return false +end + +# Start the task of an MPI processor already pinned to the thread of its inner processor. +# Without this the task is migratable, and `execute!(::ThreadProc)` then misses its inline +# fast path: it creates a second task pinned to the thread, schedules it and waits, which +# measured 160-190 us per task (a dependent chain of tasks pinned to one thread: 387 us per +# link at 4 ranks x 16 threads, of which 161 us was this hand-over). Only for processors of +# this rank, and not for a task that asked for no particular thread. `task.scope` is the +# scope the scheduler placed the task under (it includes Datadeps' exact scope and the scopes +# of chunk arguments), the same one `mpi_execute_inner` looks at. +function Dagger.Sch.task_tid_for_processor(proc::MPIProcessor{Dagger.ThreadProc}, task) + proc.rank == MPI.Comm_rank(proc.comm) || return nothing + mpi_task_thread_requested(proc, task, mpi_execution_scope(task)) || return nothing + return Dagger.Sch.task_tid_for_processor(proc.innerProc) +end + +function mpi_execution_scope(task) + # Owner elision pins the logical processor to keep result metadata equal. + # The user's original scope still decides whether a CPU thread was requested. + if hasproperty(task, :options) + state = task.options._owner_elision + state isa OwnerElisionState && state.owner >= 0 && return state.requested_scope + end + return task.scope +end + +function mpi_execute_inner(proc::MPIProcessor, f, args...; kwargs...) + if proc.innerProc isa ThreadProc && Dagger.in_task() + task = Dagger.get_tls().task_spec + if !mpi_task_thread_requested(proc, task, mpi_execution_scope(task)) + return Dagger.execute_thread_function(f, args...; kwargs...) + end + end + return execute!(proc.innerProc, f, args...; kwargs...) +end + # A task that is not part of a Datadeps region (no tag option) generates ref ids only while it # is moved to and executed on its processor, never during planning, so once `execute!` returns # nobody takes another id for its thunk id and its sub-counter is dead. Without this the table @@ -2504,7 +2942,9 @@ function mpi_execute_body(proc::MPIProcessor, f, args...; kwargs...) elseif local_rank == from_space.rank first(processors(from_space.innerSpace)) else - ThreadProc(myid(), 1) + # The first default-pool thread; thread 1 is interactive + # whenever an interactive thread exists. + ThreadProc(myid(), Dagger.first_default_tid()) end execute!(local_proc, f, raw_args...; kwargs...) space = memory_space(nothing, proc)::MPIMemorySpace @@ -2512,6 +2952,32 @@ function mpi_execute_body(proc::MPIProcessor, f, args...; kwargs...) return tochunk(nothing, proc, space; type=dest_type) end + # A communicator of one rank (a one-rank job, or a rank-local graph): nobody to tell about the + # status, the type or the space of the result, so there is nothing to plan or to broadcast + if MPI.Comm_size(proc.comm) == 1 + result = mpi_execute_inner(proc, f, raw_args...; kwargs...) + space = mpi_result_space(result, proc) + return tochunk(result, proc, space; type=typeof(result)) + end + + opts = Dagger.get_tls().task_spec.options + owner_state = opts._owner_elision + + # Captured elision is a protocol choice made at submission, independent of + # inference here. A declared concrete return type can still infer as Any or + # Union{}; ordinary metadata would have no consumer on an elided rank. + if mpi_failure_only(opts) + if islocal + # task_failed! covers failures in f and in argument movement. + result = mpi_execute_inner(proc, f, raw_args...; kwargs...) + space = mpi_result_space(result, proc) + return tochunk(result, proc, space; type=opts.return_type, _owner_elision=owner_state) + else + space = memory_space(nothing, proc)::MPIMemorySpace + return tochunk(nothing, proc, space; type=opts.return_type, _owner_elision=owner_state) + end + end + plan = mpi_execute_bcast_plan(f, args, proc) # Concrete + nothrow: type/space known locally and the call cannot throw, @@ -2519,12 +2985,12 @@ function mpi_execute_body(proc::MPIProcessor, f, args...; kwargs...) # type on every rank so chunktype stays SPMD-uniform. if !plan.need_type_bcast && plan.nothrow if islocal - result = execute!(proc.innerProc, f, raw_args...; kwargs...) + result = mpi_execute_inner(proc, f, raw_args...; kwargs...) space = mpi_result_space(result, proc) - return tochunk(result, proc, space; type=plan.inferred) + return tochunk(result, proc, space; type=plan.inferred, _owner_elision=owner_state) else space = memory_space(nothing, proc)::MPIMemorySpace - return tochunk(nothing, proc, space; type=plan.inferred) + return tochunk(nothing, proc, space; type=plan.inferred, _owner_elision=owner_state) end end @@ -2533,7 +2999,7 @@ function mpi_execute_body(proc::MPIProcessor, f, args...; kwargs...) if !plan.need_type_bcast if islocal result = try - execute!(proc.innerProc, f, raw_args...; kwargs...) + mpi_execute_inner(proc, f, raw_args...; kwargs...) catch err @opcounter :execute_bcast_send_yield bcast_meta_yield(proc.comm, proc.rank, tag, (:error, mpi_wire_exception(err))) @@ -2542,21 +3008,21 @@ function mpi_execute_body(proc::MPIProcessor, f, args...; kwargs...) @opcounter :execute_bcast_send_yield bcast_meta_yield(proc.comm, proc.rank, tag, :ok) space = mpi_result_space(result, proc) - return tochunk(result, proc, space; type=plan.inferred) + return tochunk(result, proc, space; type=plan.inferred, _owner_elision=owner_state) else msg = bcast_meta_yield(proc.comm, proc.rank, tag) if msg isa Tuple && first(msg) === :error throw(msg[2]) end space = memory_space(nothing, proc)::MPIMemorySpace - return tochunk(nothing, proc, space; type=plan.inferred) + return tochunk(nothing, proc, space; type=plan.inferred, _owner_elision=owner_state) end end # Non-concrete return type: full status + type/space (or error) broadcast if islocal result = try - execute!(proc.innerProc, f, raw_args...; kwargs...) + mpi_execute_inner(proc, f, raw_args...; kwargs...) catch err @opcounter :execute_bcast_send_yield bcast_meta_yield(proc.comm, proc.rank, tag, (:error, mpi_wire_exception(err))) @@ -2715,9 +3181,449 @@ function post_stage_array_chunks!(accel::MPIAcceleration, tasks, eltype::Type{T} return tasks end +# The block grid of an array is the same on every rank, so a block placed on one processor has a +# known rank at spawn time. The tasks that make the blocks run inside a Datadeps region (they +# cannot be elided and are not failure-only), but the tasks that read a block can: they only +# need to know who owns it (`mpi_arg_participates`). +function Dagger.note_chunk_placement!(accel::MPIAcceleration, task, scope) + if accel.comm == MPI.COMM_WORLD && scope isa Dagger.ExactScope && scope.processor isa MPIProcessor + task.placed = scope.processor.rank + end + return +end + accel_matches_proc(accel::MPIAcceleration, proc::MPIOSProc) = true accel_matches_proc(accel::MPIAcceleration, proc::MPIClusterProc) = true accel_matches_proc(accel::MPIAcceleration, proc::MPIProcessor) = true accel_matches_proc(accel::MPIAcceleration, proc) = false +# --- Owner elision -------------------------------------------------------------- +# +# Under SPMD every rank builds, places and "executes" every task, whether or not +# it takes part: a rank that neither runs a task nor owns data the task reads pays +# nearly the full planning cost (measured: 168 us against the owner's 188 us) only +# to stamp an empty result. A task qualifies for elision on a rank when +# +# * its scope is a single `ExactScope(::MPIProcessor)`, so its rank is known at +# spawn time, on every rank, without consulting the scheduler; +# * that rank is not this one, and this rank owns none of its arguments (an owner +# has to send its data, so it takes part in the move); +# * its return type is concrete (a non-concrete one needs the type broadcast to every +# rank), and it reports failures only: `execute!` then does not make the other +# ranks wait for its status (see "Failure-only task status"); +# * every argument is a plain value, an `MPIRef` chunk with no scope restriction, +# or an earlier task whose owner is known and is not this rank. +# +# Such a task skips thunk creation, scheduling, dispatch and the placeholder +# execution; the rank only takes the task id (done by `eager_spawn`, so ids and +# tags stay uniform) and builds the same placeholder result `execute!` would have. +# Uniformity checks are collective over all ranks, so they disable elision. + +# A processor of the one rank `opts` restricts a task to, or `nothing` when the scope +# allows several ranks (or is not a scope of MPI processors). Only its rank and +# communicator are meaningful: a scope that names a whole rank, as +# `Dagger.scope(mpi_rank=r)` does, leaves the choice of thread to the scheduler, and a +# rank that elides the task never learns which thread that was. `scope=` sets both +# `scope` and `compute_scope`; accept either, or both when equal. +function mpi_task_scope(opts::Options) + return if opts.compute_scope === nothing + opts.scope + elseif opts.scope === nothing || opts.scope === opts.compute_scope || opts.scope == opts.compute_scope + opts.compute_scope + else + nothing + end +end + +function mpi_scope_processor(opts::Options)::Union{Nothing,MPIProcessor} + scope = mpi_task_scope(opts) + if scope isa Dagger.ExactScope + proc = scope.processor + return proc isa MPIProcessor ? proc : nothing + elseif scope isa Dagger.UnionScope + return mpi_union_scope_processor(scope) + end + return nothing +end + +# Scopes are reused (a `with_options(scope=...)` block hands the same object to every +# task spawned under it), so what a union scope names is worked out once per scope. +# +# The key is not `objectid(scope)`: a `UnionScope` holds a tuple with one `ExactScope` per +# processor, and `objectid` hashes all of it, which made a plain rank scope +# (`Dagger.scope(mpi_rank=r)`, one entry per thread) cost time proportional to the thread +# count, several times per task. It is not the scope's address either: for a statically +# typed immutable the compiler may pass a fresh box, so an "address" can differ on every +# call and the cache would never hit. The key is a function of the contents (length and +# three members); `===` on a hit confirms it, and a miss only costs a recomputation. +# Reads take no lock: the table is replaced as a whole. +function mpi_union_key(scope::Dagger.UnionScope) + s = scope.scopes + n = length(s) + h = hash(n) + if n > 0 + h = hash(s[1], h); h = hash(s[n], h); h = hash(s[(n >> 1) + 1], h) + end + return UInt(h) +end + +mutable struct MPIUnionScopeCache + @atomic table::Dict{UInt,Tuple{Any,Any}} +end +const MPI_UNION_SCOPE_CACHE = MPIUnionScopeCache(Dict{UInt,Tuple{Any,Any}}()) +const MPI_UNION_SCOPE_CACHE_LOCK = ReentrantLock() + +function mpi_union_scope_processor(scope::Dagger.UnionScope) + key = mpi_union_key(scope) + hit = get((@atomic MPI_UNION_SCOPE_CACHE.table), key, nothing) + hit !== nothing && hit[1] === scope && return hit[2] + proc = nothing + scopes = scope.scopes + if !isempty(scopes) && all(sc -> sc isa Dagger.ExactScope && sc.processor isa MPIProcessor, scopes) + first_proc = first(scopes).processor + if all(sc -> sc.processor.rank == first_proc.rank && sc.processor.comm == first_proc.comm, scopes) + # The same processor on every rank, whatever order the scopes came in + proc = argmin(short_name, [sc.processor for sc in scopes]) + end + end + lock(MPI_UNION_SCOPE_CACHE_LOCK) do + old = @atomic MPI_UNION_SCOPE_CACHE.table + table = length(old) >= 256 ? Dict{UInt,Tuple{Any,Any}}() : copy(old) + table[key] = (scope, proc) + @atomic MPI_UNION_SCOPE_CACHE.table = table + end + return proc +end + +# At spawn time the scheduler has not yet filled in the execution or result scope +function mpi_task_processor(opts::Options)::Union{Nothing,MPIProcessor} + (opts.exec_scope === nothing && opts.result_scope === nothing) || return nothing + return mpi_scope_processor(opts) +end + +# Whether the owner of this task reports only failures (see "Failure-only task +# status"). Captured in the task's own options at submission, independently of +# later optimization/uniformity switches. Only tasks with a validated placement +# bind an owner and use this protocol. +mpi_failure_only(::Nothing) = false +mpi_failure_only(opts::Options) = + opts._owner_elision isa OwnerElisionState && opts._owner_elision.owner >= 0 +Dagger.preplaced_scope(::MPIAcceleration, opts::Options) = + mpi_failure_only(opts) ? opts._owner_elision.pinned_scope : nothing +# With the task's processor already worked out (`elide_task!` needs it for other things too) +function mpi_failure_only(opts::Options, proc::Union{Nothing,MPIProcessor}) + opts._owner_elision isa OwnerElisionState && opts.tag === nothing || return false + # Only the world communicator: ids and failure tags of other graphs are not uniform + return proc !== nothing && proc.comm == MPI.COMM_WORLD +end + +function Dagger.prepare_owner_elision!(accel::MPIAcceleration, spec, task) + accel.comm == MPI.COMM_WORLD || return + # Root submissions are rank-uniform and ordered. Other producers use the + # ordinary status protocol; their interleaving cannot define a watermark. + current_task() === Base.roottask && !Dagger.in_task() || return + @lock OWNER_ELISION_LOCK begin + if Threads.atomic_xchg!(OWNER_ELISION_DIRTY, false) + for (tid, ref) in OWNER_ELISION_STATES + ref.value === nothing && delete!(OWNER_ELISION_STATES, tid) + end + end + OWNER_ELISION_REGISTERED[] = task.uid + eligible = Dagger.ELIDE_FOREIGN_TASKS[] && !CHECK_UNIFORMITY[] && + spec.options.tag === nothing && 0 < task.uid < MPI.tag_ub() && + mpi_elision_host_type(task.metadata.return_type) + if eligible + queue = Dagger.get_options(:task_queue, Dagger.DefaultTaskQueue()) + eligible = queue isa Union{Dagger.DefaultTaskQueue,Dagger.LazyTaskQueue} + end + early = eligible ? pop!(OWNER_ELISION_EARLY, UInt32(task.uid), nothing) : nothing + if eligible + state = owner_elision_lookup(UInt32(task.uid)) + state === nothing && (state = owner_elision_register!(OwnerElisionState(UInt32(task.uid), -1, nothing))) + if early !== nothing + early.error === nothing || (@atomic state.error = early.error) + # An existing deserialized state has already counted these. + state.ready = max(state.ready, early.ready) + end + spec.options._owner_elision = state + task.owner_elision = state + end + end + return +end + +# Whether `local_rank` takes part in moving `v` to the task's rank, or cannot tell +function mpi_arg_participates(v, local_rank::Int) + if v isa Dagger.DTask + v.stub !== nothing && return mpi_arg_participates(v.stub, local_rank) + # `placed`: the rank a block of an array was put on (it does not make the task failure-only) + where = v.owner >= 0 ? v.owner : v.placed + return where < 0 || where == local_rank + elseif v isa Chunk + # N.B. A scope restriction on the chunk (a `DArray` block has one) only matters through + # `constrain(task scope, chunk scope)`, which `elide_task!` checks for the task as a whole + v.handle isa MPIRef || return true + return v.handle.rank == local_rank + elseif v isa Dagger.WeakChunk + return true + end + return false +end + +# The owner tells everyone when a failure-only task fails, whatever the cause: an +# error in the task, in moving its arguments, or an upstream failure. This runs +# under the scheduler lock, so the send is handed to another task. +function Dagger.Sch.task_failed!(::MPIAcceleration, thunk, value) + opts = thunk.options + mpi_failure_only(opts) || return + proc = opts._owner_elision.pinned_scope.processor + # An argument's source rank can fail before the owner receives its data. + # Every participating rank must publish such a failure, so the owner's + # pending receive and spectators' result fetches can both terminate. + reporter = MPI.Comm_rank(proc.comm) + ex = mpi_wire_exception(value isa Dagger.DTaskFailedException ? value.ex : value) + state = opts._owner_elision::OwnerElisionState + @atomic state.error = ex + tag = state.tid + Dagger.Sch.errormonitor_tracked("mpi_task_failed", Threads.@spawn begin + bcast_meta_yield(proc.comm, reporter, tag, OwnerFailure(ex)) + end) + return +end + +# A fetch that throws on the owner still has to take the generic id that the +# broadcast of a successful fetch takes on every other rank (see `poolget`) +function Dagger.fetch_failed_uniform!(::MPIAcceleration) + take_ref_id!() + return +end + +# --- Placement at spawn for tasks without a scope ---------------------------------- +# +# A task without a scope is placed by the scheduler, so no rank knows the owner when +# the task is created. The placement rule is deterministic and identical on every +# rank, though: the cached canonical order of the candidate processors, the rank that +# owns the task's first MPI argument moved to the front, then a rotation by the task +# id. `elide_task!` therefore applies that rule at spawn time and pins the task to the +# result with an ExactScope: the scheduler is handed a decision instead of making it, +# so it cannot disagree with the ranks that elide the task. Whatever cannot be +# decided at spawn time (an argument whose owner is unknown, a result scope, a +# processor list, a processor that rejects the function or an argument) is left to +# the scheduler and nothing is elided. + +# Rank that owns `v`, `nothing` for a plain value (the scheduler ignores those when it +# looks for the owner), `-1` when it cannot be told at spawn time +function mpi_arg_owner(v) + if v isa Dagger.DTask + v.stub !== nothing && return mpi_arg_owner(v.stub) + return v.owner >= 0 ? v.owner : v.placed + elseif v isa Chunk + v.handle isa MPIRef || return -1 + return v.handle.rank + elseif v isa Dagger.WeakChunk + return -1 + end + return nothing +end + +function mpi_preplace!(accel::MPIAcceleration, spec, task) + opts = spec.options + state = Dagger.Sch.EAGER_STATE[] + state === nothing && return false + # Match the scheduler's option defaults before proving eligibility. Defaults + # may restrict processors even when the caller supplied only a rank scope. + Dagger.options_merge!(opts, state.sch_options) + fargs = spec.fargs + for arg in fargs + Dagger.ispositional(arg) || return false + end + sig = Dagger.Signature(Any[chunktype(Dagger.value(arg)) for arg in fargs]) + Base.invokelatest(Dagger.populate_defaults!, opts, sig) + opts.exec_scope === nothing && opts.result_scope === nothing && opts.proclist === nothing && + (opts.single === nothing || opts.single == 0) && opts.restore === nothing && + opts.tag === nothing || return false + opts.checkpoint === nothing || return false + opts.get_result === true && return false + opts.meta === true && return false + (opts.syncdeps === nothing || isempty(opts.syncdeps)) || return false + scope = if opts.compute_scope === nothing + opts.scope + elseif opts.scope === nothing || opts.scope === opts.compute_scope || opts.scope == opts.compute_scope + opts.compute_scope + else + return false + end + scope === nothing && (scope = Dagger.DefaultScope()) + f = Dagger.value(fargs[1]) + (f isa Function || f isa Type) || return false + pref = nothing + for i in 2:length(fargs) + arg = fargs[i] + Dagger.ispositional(arg) || return false + owner = mpi_arg_owner(Dagger.value(arg)) + owner === nothing && continue + owner < 0 && return false + pref === nothing && (pref = owner) + end + for i in 2:length(fargs) + val = Dagger.value(fargs[i]) + val isa Chunk || continue + scope = Dagger.constrain(scope, val.scope) + scope isa Dagger.InvalidScope && return false + end + ctx = Dagger.Sch.eager_context() + procs = Dagger.@reusable_vector :mpi_elision_procs Processor OSProc() 32 + for candidate in Dagger.Sch.procs_to_use(ctx, state.sch_options) + haskey(state.worker_chans, root_worker_id(candidate)) && push!(procs, candidate) + end + isempty(procs) && return false + # The scheduler's own rule (`schedule_one!`): the compatible processors, re-ordered under uniform + # execution by the canonical key with the owner of the first MPI argument in front, then rotated by the id + candidates = Dagger.Sch.compatible_processors_ordered(accel, scope, procs) + isempty(candidates) && return false + # Only the first candidate is needed. Select the same preferred rank/ring + # offset as place_processors_uniform!, without copying or rotating the cache. + lo, hi = 1, length(candidates) + if pref !== nothing + first_pref, last_pref = Dagger.preferred_processor_range(candidates, accel, pref) + if first_pref <= last_pref + lo, hi = first_pref, last_pref + end + end + proc = candidates[lo + mod(Int(task.uid) - 1, hi - lo + 1)] + proc isa MPIProcessor || return false + proc.innerProc isa ThreadProc || return false + # What `can_use_proc` would check of the processor the scheduler picks first + Dagger.proc_in_scope(proc, scope) || return false + Base.invokelatest(Dagger.iscompatible_func, proc, opts, typeof(f)) || return false + for i in 2:length(fargs) + Base.invokelatest(Dagger.iscompatible_arg, proc, opts, chunktype(Dagger.value(fargs[i]))) || return false + # The scheduler also constrains the task's scope by that of every chunk argument + val = Dagger.value(fargs[i]) + val isa Chunk && !Dagger.proc_in_scope(proc, val.scope) && return false + end + pinned = Dagger.ExactScope(proc) + opts._owner_elision.requested_scope = scope + opts._owner_elision.pinned_scope = pinned + return true +end + +# The scheduler constrains a task's scope by the scope of every chunk argument and fails the task when they +# cannot be satisfied together; a rank that elides the task only needs to know that they can. The result scope is +# `nothing` for every task that gets here (`mpi_task_processor` refuses one), so the chain starts from the compute scope. +# N.B. Computed only for chunk arguments that carry a restriction: `constrain` on the union scope of a whole rank +# costs time proportional to its size, which showed up as +30 us per task at 16 threads when it ran for every task. +function mpi_chunk_scopes_fit(opts::Options, fargs) + scope = nothing + for i in 2:length(fargs) + val = Dagger.value(fargs[i]) + val isa Chunk || continue + val.scope isa Dagger.AnyScope && continue + scope === nothing && (scope = @something(opts.compute_scope, opts.scope, Dagger.DefaultScope())) + scope = Dagger.constrain(scope, val.scope) + scope isa Dagger.InvalidScope && return false + end + return true +end + +function Dagger.elide_task!(accel::MPIAcceleration, spec, task) + try + return mpi_elide_task!(accel, spec, task) + finally + state = spec.options._owner_elision + if state isa OwnerElisionState && state.owner < 0 + spec.options._owner_elision = nothing + task.owner_elision = nothing + end + end +end + +# A placeholder may use the predicted processor's host space only when the +# actual result cannot introduce another backend. Custom structs and GPU values +# need the normal metadata exchange, even with a concrete declared return type. +mpi_elision_host_type(T) = isconcretetype(T) && T !== Union{} && + ((isbitstype(T) && parentmodule(T) in (Core, Base)) || + T === String || T === Symbol || T <: Array) + +function mpi_elide_task!(accel::MPIAcceleration, spec, task) + # Placement, ids and failure tags here are those of the world communicator only + accel.comm == MPI.COMM_WORLD || return false + opts = spec.options + T = task.metadata.return_type + mpi_elision_host_type(T) || return false + # An explicit scope that permits several ranks stays a scheduler decision. + mpi_task_scope(opts) === nothing || mpi_scope_processor(opts) !== nothing || return false + # Use the scheduler's registered candidate set and compatibility predicates + # for every scope, then pin the proven decision. A union's syntactic members + # alone do not account for disabled/custom/incompatible processors. + mpi_preplace!(accel, spec, task) || return false + proc = opts._owner_elision.pinned_scope.processor + proc === nothing && return false + proc.innerProc isa ThreadProc || return false + # Later submissions use this to decide about their own arguments, and `fetch` + # to stay uniform when the task fails. Only failure-only tasks have an owner. + mpi_failure_only(opts, proc) || return false + opts._owner_elision.owner = proc.rank + task.owner = proc.rank + local_rank = MPI.Comm_rank(proc.comm) + proc.rank == local_rank && return false + (opts.syncdeps === nothing || isempty(opts.syncdeps)) || return false + opts.restore === nothing || return false + fargs = spec.fargs + f = Dagger.value(fargs[1]) + (f isa Function || f isa Type) || return false + for i in 2:length(fargs) + arg = fargs[i] + Dagger.ispositional(arg) || return false + mpi_arg_participates(Dagger.value(arg), local_rank) && return false + end + mpi_chunk_scopes_fit(opts, fargs) || return false + # The placeholder `execute!` stamps on a non-owner, with the id it would get, on the + # processor the owner will run it on + space = memory_space(nothing, proc)::MPIMemorySpace + # N.B. `execute!` first takes a ref id for the task's tag when the task has no + # tag option (`to_tag()`), so the result chunk is the second id of its task. + # The owner builds the real chunk with that id, and every rank must agree on it. + stub = with(DATADEPS_THUNK_ID => Int64(task.uid)) do + opts.tag === nothing && take_ref_id!() + tochunk(nothing, proc, space; type=T, _owner_elision=opts._owner_elision) + end + mpi_cleanup_tid(task.uid) + task.stub = stub + put!(task.future, stub) + return true +end + +function Dagger.skip_tasks!(accel::MPIAcceleration, n::Integer) + n >= 0 || throw(ArgumentError("cannot skip a negative number of tasks")) + n == 0 && return nothing + # Without elision the owner announces every task's result type to ALL ranks, which a rank that never planned the task + # cannot receive; only failure-only (elided) tasks may be skipped. + Dagger.ELIDE_FOREIGN_TASKS[] || throw(ArgumentError("`Dagger.skip_tasks!` needs foreign-task elision: call `Dagger.elide_foreign_tasks!(true)` first")) + CHECK_UNIFORMITY[] && throw(ArgumentError("`Dagger.skip_tasks!` cannot skip collective uniformity checks; disable them first")) + accel.comm == MPI.COMM_WORLD || throw(ArgumentError("`Dagger.skip_tasks!` is only supported for the world communicator")) + current_task() === Base.roottask && !Dagger.in_task() || + throw(ConcurrencyViolationError("`Dagger.skip_tasks!` requires ordered root submissions")) + # Validate before initialization too: the eager scheduler consumes one id. + # Normalize only after bounding n, so every Integer width is accepted and + # an oversized BigInt cannot overflow either conversion or the counter. + initialize = Dagger.Sch.EAGER_STATE[] === nothing + counter = Dagger.ID_COUNTER[] + remaining = MPI.tag_ub() - counter - Int(initialize) + counter > 0 && n <= remaining || throw(ArgumentError("skipped task ids exceed the MPI tag range")) + count = Int(n) + initialize && Dagger.Sch.init_eager() + first_id = Threads.atomic_add!(Dagger.ID_COUNTER, count) + # Skipped ids are registrations too: no later handle can consume failure + # notifications for them. Advance the early-delivery watermark and drop + # only messages at or below it; retain states for existing live handles. + @lock OWNER_ELISION_LOCK begin + OWNER_ELISION_REGISTERED[] = max(OWNER_ELISION_REGISTERED[], UInt(first_id + count - 1)) + for tid in keys(OWNER_ELISION_EARLY) + UInt(tid) <= OWNER_ELISION_REGISTERED[] && delete!(OWNER_ELISION_EARLY, tid) + end + end + return nothing +end + end # module MPIExt diff --git a/ext/PythonExt.jl b/ext/PythonExt.jl index 9783c9f48..3b3156ad9 100644 --- a/ext/PythonExt.jl +++ b/ext/PythonExt.jl @@ -16,6 +16,11 @@ struct PythonProcessor <: Processor owner::Int end +# PythonCall initializes its interpreter on the importing Julia thread, which +# need not be thread 1. Discover that thread once rather than sharing its +# request/response channel for every task execution. +const PYTHON_GIL_THREAD = Ref{Int}(0) + Dagger.root_worker_id(proc::PythonProcessor) = proc.owner Dagger.get_parent(proc::PythonProcessor) = OSProc(proc.owner) Dagger.default_enabled(::PythonProcessor) = true @@ -38,17 +43,58 @@ function Dagger.execute!(::PythonProcessor, f, args...; kwargs...) # CPython requires that the GIL is held by the calling thread. By default # the GIL is held by the thread that initialized Python (the main thread), # so calling into Python from a Dagger worker thread without the GIL - # segfaults. Mirror PythonCall's own approach (see `Base.propertynames`): + # segfaults. Like PythonCall's own approach (see `Base.propertynames`), # if the current thread holds the GIL, call directly; otherwise hand the # call off to the GIL-holding main thread. if PythonCall.C.PyGILState_Check() == 1 return f(args...; kwargs...) else - return PythonCall.C.on_main_thread(() -> f(args...; kwargs...)) + # PythonCall's shared request/response channels neither associate a + # reply with its caller nor keep exception rendering on the GIL owner. + # A private task gives each invocation its own result, including when + # its waiter is cancelled. Return exceptions as values so fetch does + # not render a Python exception on the waiting CPU thread. + # The old Python helper did not run with Dagger TLS. Keep that + # behavior: a cancelled caller can recycle its pooled task metadata + # while this Python invocation is still finishing. + logging = Dagger.task_logging_enabled() + task_id = logging ? (Dagger.task_id()::Int) : 0 + task = Task() do + try + PythonCall.C.PyGILState_Check() == 1 || error("Python's interpreter thread no longer holds the GIL") + if logging + Dagger.TimespanLogging.prof_task_put!(task_id) + end + Some(f(args...; kwargs...)) + catch err + CapturedException(err, catch_backtrace()) + end + end + Dagger.set_task_tid!(task, PYTHON_GIL_THREAD[]) + schedule(task) + response = fetch(task) + if response isa CapturedException + response.ex isa InterruptException && throw(response.ex) + throw(response) + end + return something(response) end end +# CPU work stealing can select Python work through ThreadProc's broad +# compatibility predicate. Keep the CPU execution's profiling/error handling, +# but invoke Python through the same GIL-safe path as its own processor. +function Dagger.execute!(proc::ThreadProc, f::Py, args...; kwargs...) + return Dagger.execute_thread_function(Dagger.execute!, PythonProcessor(proc.owner), + f, args...; kwargs...) +end + function __init__() + PYTHON_GIL_THREAD[] = if PythonCall.C.PyGILState_Check() == 1 + Threads.threadid() + else + PythonCall.C.on_main_thread(Threads.threadid)::Int + end Dagger.add_processor_callback!(:pythonproc) do return PythonProcessor(myid()) end diff --git a/src/Dagger.jl b/src/Dagger.jl index 2b988a956..a9525bc90 100644 --- a/src/Dagger.jl +++ b/src/Dagger.jl @@ -222,7 +222,11 @@ function __init__() end end end - for tid in 1:Threads.nthreads() + # Not `1:Threads.nthreads()`: that counts the default pool but numbers it + # from 1, which is wrong whenever an interactive thread exists (it takes + # thread 1). We would then run tasks on the interactive thread and never + # on the last default thread. + for tid in default_pool_tids() add_processor_callback!("__cpu_thread_$(tid)__") do ThreadProc(myid(), tid) end diff --git a/src/acceleration.jl b/src/acceleration.jl index e4eea0973..c8bd20e50 100644 --- a/src/acceleration.jl +++ b/src/acceleration.jl @@ -75,6 +75,18 @@ compatible_processors(accel::Union{Acceleration,Nothing}, scope::AbstractScope=g uniform_execution(::DistributedAcceleration) = false uniform_execution() = uniform_execution(current_acceleration()) +""" + fetch_failed_uniform!(accel) + +Called when `fetch` of a task with a known owner (`DTask.owner`) throws because the +task failed on this process. Under uniform execution a fetch of a task that did +not fail takes part in a broadcast, which takes a task-id-derived tag on every +process; a process that fails before it gets there must take the same ids, or the +ids (and tags) of everything that follows differ across processes. Does nothing +by default. +""" +fetch_failed_uniform!(::Acceleration) = nothing + # SPMD uniformity checking. Under a uniform-execution acceleration (e.g. MPI), # planning-time values are hashed and compared across ranks to catch divergence # early. Core datadeps calls `check_uniform` unconditionally; the real checks @@ -124,6 +136,12 @@ cleanup_tasks_accel!(accel::Acceleration, tasks) = foreach(t -> cleanup_task_accel!(accel, t), tasks) schedule_argument_move(::Acceleration, ::Integer, f::Function) = Threads.@spawn f() +schedule_argument_move(accel::Acceleration, id::Integer, f::Function, ::Options, value) = + schedule_argument_move(accel, id, f) + +# A proven placement may narrow the scheduler's effective scope without +# rewriting the user options observed by custom compatibility predicates. +preplaced_scope(::Acceleration, ::Options) = nothing """ sched_move(accel, to_proc, value) -> Any @@ -312,6 +330,35 @@ default_procgrid(accel, nblocks::NTuple{N,Int}) where N = nothing "Acceleration-specific finalization after array chunk tasks are spawned." post_stage_array_chunks!(accel::Acceleration, tasks, eltype::Type, nd::Int) = tasks +""" + note_chunk_placement!(accel, task::DTask, scope) + +Called for every task that produces a block of an array, with the compute scope the block was +placed with (a single processor for the deterministic placements: every rank computes the same +grid). An acceleration that wants to know at spawn time where a block lives records it here; +the default does nothing. +""" +note_chunk_placement!(::Acceleration, task, scope) = nothing + +""" + skip_tasks!(n) + +Under MPI every rank plans every task, and a task's id (and so its MPI tags) is the next value of a counter +that must be equal on all ranks. A rank that does not take part in a task (it neither runs it nor owns one +of its arguments) can leave the `@spawn` out and call `skip_tasks!(1)` at that position instead (or +`skip_tasks!(k)` for `k` consecutive foreign tasks): it advances the task id counter by `n` without planning +the omitted tasks. Needs foreign-task elision ([`elide_foreign_tasks!`](@ref)), disabled uniformity checks, +and an ordered root call on the world communicator. Counts must be nonnegative and fit the remaining MPI +tag range; rejected calls leave scheduler state and ids unchanged. A zero count does nothing. +Constraints that are not checked: every rank must make the same sequence of `@spawn` / `skip_tasks!` +calls per task position; a skipped task must be one that this rank would have elided (a concrete `return_type`, +no `tag`, and its result is never used on this rank), because the rank has no placeholder for it and a failure of +the task has no observer there. Failure notifications for skipped ids are discarded. Other accelerations +have no uniform ids: a no-op. +""" +skip_tasks!(n::Integer) = skip_tasks!(current_acceleration(), n) +skip_tasks!(::Acceleration, n::Integer) = nothing + default_processor(space::CPURAMMemorySpace) = OSProc(space.owner) default_memory_space(accel::DistributedAcceleration) = CPURAMMemorySpace(myid()) # Chunk records must be labeled with the space the value actually resides in diff --git a/src/array/darray.jl b/src/array/darray.jl index 32d64275a..2f1fa3f5f 100644 --- a/src/array/darray.jl +++ b/src/array/darray.jl @@ -617,7 +617,7 @@ function stage(ctx::Context, d::Distribute) shape = size(chunks) scope = procgrid_scope(d.procgrid, I) options = Options(compute_scope=scope) - Dagger.spawn(options, shape, chunks...) do shape, parts... + t = Dagger.spawn(options, shape, chunks...) do shape, parts... if prod(shape) == 0 return Array{T}(undef, shape) end @@ -625,6 +625,8 @@ function stage(ctx::Context, d::Distribute) ps = reshape(Any[parts...], shape) collect(treereduce_nd(dimcatfuncs, ps)) end + note_chunk_placement!(current_acceleration(), t, scope) + t end cs = post_stage_array_chunks!(current_acceleration(), cs, T, Nd) else diff --git a/src/dtask.jl b/src/dtask.jl index 29fecce51..3b41db3f8 100644 --- a/src/dtask.jl +++ b/src/dtask.jl @@ -74,16 +74,26 @@ mutable struct DTask uid::UInt future::ThunkFuture metadata::DTaskMetadata + # Result placeholder of a task this process never built a `Thunk` for (see + # `elide_task!`); `nothing` for every ordinary task. + stub::Any + # Rank/worker known to own this task's result at spawn time, `-1` when unknown + owner::Int + # Rank/worker the placement code (`emit_chunk_tasks!`) put this task's result on, `-1` when + # not known at spawn time. Unlike `owner` it changes nothing about `fetch`; it only lets an + # acceleration decide about the *consumers* of the result (see `note_chunk_placement!`). + placed::Int + owner_elision::Any thunk_ref::DRef - DTask(uid, future, metadata) = new(uid, future, metadata) + DTask(uid, future, metadata) = new(uid, future, metadata, nothing, -1, -1, nothing) end const EagerThunk = DTask Base.isready(t::DTask) = isready(t.future) Base.istaskdone(t::DTask) = isready(t.future) -Base.istaskstarted(t::DTask) = isdefined(t, :thunk_ref) +Base.istaskstarted(t::DTask) = t.stub !== nothing || isdefined(t, :thunk_ref) function Base.wait(t::DTask) if !istaskstarted(t) throw(ConcurrencyViolationError("Cannot `wait` on an unlaunched `DTask`")) @@ -95,6 +105,18 @@ function Base.fetch(t::DTask; raw=false, move_value=!raw, unwrap=!raw, uniform=f if !istaskstarted(t) throw(ConcurrencyViolationError("Cannot `fetch` an unlaunched `DTask`")) end + if t.owner >= 0 + # The owner learns of a failure from its own task, every other process from + # a message, and a fetch must do the same on all of them: see + # `fetch_failed_uniform!` + value = try + fetch(t.future; move_value=false, unwrap=false, uniform) + catch + move_value && fetch_failed_uniform!(current_acceleration()) + rethrow() + end + return move_value ? move(OSProc(), value) : value + end return fetch(t.future; move_value, unwrap, uniform) end function waitany(tasks::Vector{DTask}) diff --git a/src/memory-spaces.jl b/src/memory-spaces.jl index 0b43e212d..9722da625 100644 --- a/src/memory-spaces.jl +++ b/src/memory-spaces.jl @@ -138,6 +138,30 @@ copy: the buffer's contents are established later by Datadeps' copy-to phase. alloc_uninit(::CPURAMMemorySpace, ::Type{<:Array{T,N}}, dims::Dims{N}) where {T,N} = alloc_libc_array(T, dims) +""" + tune_malloc!() -> Bool + +Keep freed memory in the process heap instead of returning it to the system (glibc only): a +buffer of up to 16 MB comes from the heap, not from its own `mmap`, and the heap's free top is +not trimmed. Datadeps slots and received tiles are libc buffers of tens to hundreds of KB that +are allocated and freed in every region; with glibc's defaults each one is a fresh `mmap` or a +trimmed heap top, so every use pays page faults (received tiles at ~0.7 GB/s). Apply explicitly with `Dagger.tune_malloc!()` if this process should retain freed tile buffers. +MPI activation leaves the allocator policy unchanged. Returns whether the settings were applied; +a no-op elsewhere. +""" +function tune_malloc!() + Sys.islinux() || return false + try + # mallopt parameters: M_TRIM_THRESHOLD = -1, M_TOP_PAD = -2, M_MMAP_THRESHOLD = -3 + ok = ccall(:mallopt, Cint, (Cint, Cint), -3, 16 << 20) == 1 + ok &= ccall(:mallopt, Cint, (Cint, Cint), -1, typemax(Int32)) == 1 + ok &= ccall(:mallopt, Cint, (Cint, Cint), -2, 256 << 20) == 1 + return ok + catch + return false + end +end + """ slot_may_be_uninit(from_space, to_space, ::Type{T}) -> Bool diff --git a/src/options.jl b/src/options.jl index 32fd7a685..8b984798c 100644 --- a/src/options.jl +++ b/src/options.jl @@ -77,6 +77,9 @@ Base.@kwdef mutable struct Options writes::Union{Vector{Int},Nothing} = nothing return_type::Union{Type,Nothing} = nothing + + # Private acceleration state captured at submission, never propagated to children. + _owner_elision = nothing end Options(::Nothing) = Options() function Options(old_options::NamedTuple) diff --git a/src/precompile.jl b/src/precompile.jl index c149eee62..d5adb1a2d 100644 --- a/src/precompile.jl +++ b/src/precompile.jl @@ -1,7 +1,13 @@ @compile_workload begin system_uuid() - add_processor_callback!("__cpu_thread_1__") do - ThreadProc(1, 1) + # `__init__` has not run yet, so register the one thread the workload + # needs (the default pool's first, which is not thread 1 when an + # interactive thread exists), and remove it again below: this Dict is + # saved in the package image, and `__init__` registers the real threads. + precompile_tid = first_default_tid() + precompile_cb = Symbol("__cpu_thread_$(precompile_tid)__") + add_processor_callback!(precompile_cb) do + ThreadProc(1, precompile_tid) end # FIXME: t1 = @spawn 1+1 t1 = spawn(+, 1, 1) @@ -105,6 +111,7 @@ @assert isempty(Sch.WORKER_MONITOR_CHANS) @assert isempty(Sch.WORKER_MONITOR_TASKS) ID_COUNTER[] = 1 + delete_processor_callback!(precompile_cb) # Clear the precompile-time UUID cache so it is not baked into the compiled # image; __init__ re-populates it from the shared UUID file at load time. delete!(SYSTEM_UUIDS, myid()) diff --git a/src/procgrid.jl b/src/procgrid.jl index c23d311b8..7aaf3b738 100644 --- a/src/procgrid.jl +++ b/src/procgrid.jl @@ -101,9 +101,21 @@ function build_procgrid(assignment::AssignmentType{N}, sizeA::NTuple{N,Int}, error("Unsupported assignment symbol: $assignment, use :arbitrary, :blockrow, :blockcol, :cyclicrow or :cycliccol") end elseif assignment isa AbstractArray{<:Int, N} - missingprocs = filter(p -> p ∉ procs(), assignment) + available_workers = procs() + missingprocs = filter(p -> p ∉ available_workers, assignment) isempty(missingprocs) || error("Specified workers are not available: $missingprocs") - return DenseProcGrid([ThreadProc(proc, 1) for proc in assignment]) + if length(assignment) <= 1 + return DenseProcGrid([first_thread_proc(pid) for pid in assignment]) + end + # Match the grid's element type so repeated entries reuse the same box. + first_procs = Dict{Int,Processor}() + grid = Array{Processor,N}(undef, size(assignment)) + for (index, pid) in enumerate(assignment) + grid[index] = get!(first_procs, pid) do + first_thread_proc(pid) + end + end + return DenseProcGrid{N}(grid) elseif assignment isa AbstractArray{<:Processor, N} missingprocs = filter(p -> p ∉ availprocs, assignment) isempty(missingprocs) || error("Specified processors are not available: $missingprocs") @@ -121,6 +133,7 @@ function emit_chunk_tasks!(domainchunks, procgrid, eltype::Type{T}, spawn_chunk: scope = procgrid === nothing ? default_scope : procgrid_scope(procgrid, I) i = LinearIndices(domainchunks)[I] tasks[i] = spawn_chunk(scope, I, i) + note_chunk_placement!(current_acceleration(), tasks[i], scope) end end # Under SPMD/MPI (uniform execution) the chunk-placement tasks must run diff --git a/src/sch/Sch.jl b/src/sch/Sch.jl index 8fce00ca0..ecbcd3184 100644 --- a/src/sch/Sch.jl +++ b/src/sch/Sch.jl @@ -1037,6 +1037,7 @@ concurrently across threads. options = task.options Dagger.options_merge!(options, state.sch_options) Dagger.populate_defaults!(options, sig) + accel = something(options.acceleration, current_acceleration()) # Calculate scope. Errors are stored in `scope_ex` and applied in Phase 3. local scope @@ -1069,6 +1070,14 @@ concurrently across threads. end end + if scope_ex === nothing + preplaced = Dagger.preplaced_scope(accel, options) + if preplaced !== nothing + scope = constrain(scope, preplaced) + scope isa InvalidScope && (scope_ex = SchedulingException("Preplaced processor is outside the task scope")) + end + end + if scope_ex !== nothing # scope is invalid — fail the task under state.lock (set_failed! requires it) lock(state.lock) do @@ -1086,8 +1095,6 @@ concurrently across threads. # 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 @@ -1783,6 +1790,15 @@ proc_state(proc::Processor) = proc_state(Dagger.get_tls().sch_uid, proc) task_tid_for_processor(::Processor) = nothing task_tid_for_processor(proc::Dagger.ThreadProc) = proc.tid +""" + task_tid_for_processor(proc, task) + +Return `nothing` for a migratable task, or the fixed thread assigned to `proc`. +An acceleration wrapping a `ThreadProc` can opt individual tasks into that +processor's pinned launch path. Every non-`nothing` result for a given processor +must name the same thread: pooled tasks are pinned once and reused. +""" +task_tid_for_processor(proc::Processor, task) = task_tid_for_processor(proc) stealing_permitted(::Processor) = true stealing_permitted(proc::Dagger.ThreadProc) = proc.owner != 1 || proc.tid != 1 @@ -1965,16 +1981,23 @@ function start_processor_runner!(istate::ProcessorInternalState, uid::UInt64, re # completes before the record exists, and DoTaskSpec's cleanup # loop then burned a sleep(0.1) per lost race — the dominant # multithreaded wall-time cost for small tasks. - @reusable_tasks :start_processor_runner!_task_cache 32 t->begin - tid = task_tid_for_processor(to_proc) - if tid !== nothing - Dagger.set_task_tid!(t, tid) - else - Dagger.set_task_migratable!(t) + # N.B. A pooled task is pinned (or made migratable) once, when its slot is created, and the + # slot is then reused for later tasks. The thread decision can differ per task (an + # acceleration that pins only the tasks that asked for a thread), so tasks that start + # pinned and tasks that start migratable must not share slots: a migratable task that + # reused a pinned slot would stay bound to that thread. + task_tid = task_tid_for_processor(to_proc, task) + if task_tid === nothing + @reusable_tasks :start_processor_runner!_task_cache_migratable 32 t->Dagger.set_task_migratable!(t) "thunk" DoTaskSpec(to_proc, return_queue, task, cancel_token) t->begin + lock(istate.queue) do _ + tasks[thunk_id] = t + end end - end "thunk" DoTaskSpec(to_proc, return_queue, task, cancel_token) t->begin - lock(istate.queue) do _ - tasks[thunk_id] = t + else + @reusable_tasks :start_processor_runner!_task_cache 32 t->Dagger.set_task_tid!(t, task_tid) "thunk" DoTaskSpec(to_proc, return_queue, task, cancel_token) t->begin + lock(istate.queue) do _ + tasks[thunk_id] = t + end end end end @@ -2259,6 +2282,7 @@ struct MoveCtx{A<:Dagger.Acceleration,P<:Processor} to_proc::P thunk_id::Int f::Any + options::Options end """ @@ -2276,7 +2300,7 @@ function maybe_async_move!(arg, mctx::MoveCtx) end #=FIXME:REALLOC_TASKS=# return schedule_argument_move(mctx.accel, mctx.thunk_id, - () -> move_one_argument!(arg, mctx)) + () -> move_one_argument!(arg, mctx), mctx.options, Dagger.value(arg)) end function move_one_argument!(arg, mctx::MoveCtx) @@ -2450,7 +2474,7 @@ Executes a single task specified by `task` on `to_proc`. # rank-uniform tags derived from the thunk ID; they must run sequentially # in argument order (FIFO tag matching), with the thunk's TID in scope accel = something(options.acceleration, current_acceleration()) - mctx = MoveCtx(ctx, accel, to_proc, thunk_id, f) + mctx = MoveCtx(ctx, accel, to_proc, thunk_id, f, options) fetch_tasks = nothing for arg in _data t = maybe_async_move!(arg, mctx) diff --git a/src/sch/eager.jl b/src/sch/eager.jl index 69c5b6d87..0237ce37b 100644 --- a/src/sch/eager.jl +++ b/src/sch/eager.jl @@ -45,7 +45,9 @@ function init_eager() # wakes up. Further testing is needed. sched_task = @task try sopts = SchedulerOptions(;allow_errors=true) - opts = Dagger.Options((;scope=Dagger.ExactScope(Dagger.ThreadProc(1, 1)), + # The first default-pool thread, not thread 1: when an interactive + # thread exists it is thread 1, and Dagger has no processor for it. + opts = Dagger.Options((;scope=Dagger.ExactScope(Dagger.ThreadProc(1, Dagger.first_default_tid())), occupancy=Dict(Dagger.ThreadProc=>0), time_util=Dict(Dagger.ThreadProc=>0))) Dagger.compute(ctx, Dagger._delayed(eager_thunk, opts)(); diff --git a/src/sch/util.jl b/src/sch/util.jl index 50a7a6d1c..e63c65f1e 100644 --- a/src/sch/util.jl +++ b/src/sch/util.jl @@ -115,8 +115,25 @@ function store_result!(state, thunk, value; error::Bool=false) thunk.cache_ref = Some{Any}(value) end @atomic thunk.errored = error + error && task_failed!(thunk, value) return true end + +""" + task_failed!(thunk, value) + +Called once, by whoever recorded the failure of `thunk` (its own error or an +upstream's), while the scheduler lock is held. Accelerations whose other +processes cannot see this failure on their own override it for the tasks they +need to tell; it must not block. Does nothing by default. +""" +function task_failed!(thunk, value) + accel = thunk.options.acceleration + accel === nothing || task_failed!(accel, thunk, value) + return +end +task_failed!(::Dagger.Acceleration, thunk, value) = nothing + function clear_result!(state, thunk) @assert islocked(state.lock) thunk.cache_ref = nothing diff --git a/src/scopes.jl b/src/scopes.jl index 1cbf7a703..8b9bae6a3 100644 --- a/src/scopes.jl +++ b/src/scopes.jl @@ -20,6 +20,10 @@ Base.:(==)(ts1::TaintScope, ts2::TaintScope) = length(ts1.taints) == length(ts2.taints) && all(collect(ts1.taints) .== collect(ts2.taints)) +# Equality compares taint contents; the backing Set's identity is immaterial. +Base.hash(scope::TaintScope, h::UInt) = + hash(scope.taints, hash(scope.scope, hash(TaintScope, h))) + struct DefaultEnabledTaint <: AbstractScopeTaint end "Default scope that contains the set of `default_enabled` processors." @@ -29,9 +33,20 @@ const DEFAULT_SCOPE_INSTANCE = TaintScope(AnyScope(), Set{AbstractScopeTaint}([DefaultEnabledTaint()])) DefaultScope() = DEFAULT_SCOPE_INSTANCE +""" + record_union_scope_members!(scope, members) -> nothing + +Acceleration hook called by `UnionScope` after flattening and deduplicating its +members. `members::Set{AbstractScope}` is temporary constructor-owned membership +data; an implementation may retain it or its backing storage without mutating +it. The default does nothing. Implementations return `nothing`. +""" +record_union_scope_members!(::AbstractScope, ::Set{AbstractScope}) = nothing + "Union of two or more scopes." struct UnionScope <: AbstractScope scopes::Tuple + membership_hash::UInt function UnionScope(scopes::Tuple) scope_set = Set{AbstractScope}() for scope in scopes @@ -46,13 +61,32 @@ struct UnionScope <: AbstractScope if isempty(scope_set) throw(ArgumentError("Cannot construct UnionScope with no inner scopes")) end - return new((collect(scope_set)...,)) + membership_hash = zero(UInt) + for inner in scope_set + membership_hash ⊻= hash(inner)::UInt + end + result = new((collect(scope_set)...,), membership_hash) + record_union_scope_members!(result, scope_set) + return result end end UnionScope(scopes...) = UnionScope((scopes...,)) UnionScope(scopes::Vector{<:AbstractScope}) = UnionScope((scopes...,)) UnionScope(s::AbstractScope) = UnionScope((s,)) UnionScope() = UnionScope(()) +# Equality ignores member order. Hash the tuple contents commutatively without +# constructing another set. The retained UInt adds no mutable identity to the +# scope: equivalent tuple constructions still share Sch objectid/=== cache keys. +Base.hash(scope::UnionScope, h::UInt) = hash(scope.membership_hash, hash(UnionScope, h)) +# Derived hashes depend on the receiving process's member identities. Send +# normalized members only and rebuild metadata/cache registration on receipt. +function Serialization.serialize(s::AbstractSerializer, scope::UnionScope) + Serialization.serialize_type(s, UnionScope) + Serialization.serialize(s, scope.scopes) +end +Serialization.deserialize(s::AbstractSerializer, ::Type{UnionScope}) = + UnionScope(Serialization.deserialize(s)) + proc_in_scope(proc::Processor, scope::UnionScope) = any(subscope->proc_in_scope(proc, subscope), scope.scopes) @@ -222,6 +256,11 @@ function constrain(x::UnionScope, y::UnionScope) isempty(zs) && return InvalidScope(x, y) UnionScope(zs) end +# Everything is allowed by `AnyScope`: the answer is `x` itself. Without this the generic method below wraps `AnyScope` in a +# union and rebuilds a new `UnionScope` of all of `x`'s scopes (a `Set`, hashing, a fresh tuple): for the union of one rank's +# processors that was ~90 us and 11 KB of garbage for every task the scheduler placed (`schedule_one!` constrains the compute +# scope by `AnyScope()` when there is no result scope). +constrain(x::UnionScope, ::AnyScope) = x constrain(x::UnionScope, y) = constrain(x, UnionScope((y,))) Base.isless(::NodeScope, ::NodeScope) = false @@ -515,4 +554,4 @@ function Base.issubset(scope1::AbstractScope, scope2::AbstractScope) proc in scope2_procs || return false end return true -end \ No newline at end of file +end diff --git a/src/submission.jl b/src/submission.jl index 99ba2634b..d6a546ff3 100644 --- a/src/submission.jl +++ b/src/submission.jl @@ -185,11 +185,17 @@ eager_submit_internal!(ctx, state, task, tid, payload::Tuple{<:AnyPayload}) = lock(state.thunk_dict) local thunk try - thunk = Dagger.payload(state.thunk_dict)[dep.id.id] + # N.B. A task elided on this process has no thunk and is already + # finished: it contributes no edge + thunk = get(Dagger.payload(state.thunk_dict), dep.id.id, nothing) finally unlock(state.thunk_dict) end - @inbounds syncdeps_vec[idx] = ThunkSyncdep(thunk) + @inbounds syncdeps_vec[idx] = thunk === nothing ? ThunkSyncdep() : ThunkSyncdep(thunk) + end + # Drop the placeholders left for elided tasks + if any(dep -> dep.id === nothing && dep.thunk === nothing, syncdeps_vec) + filter!(dep -> !(dep.id === nothing && dep.thunk === nothing), syncdeps_vec) end if !isempty(syncdeps_vec) || any(arg->istask(value(arg)), fargs) if options.syncdeps === nothing @@ -397,7 +403,10 @@ function eager_process_elem_submission_to_local!(arg::Argument) @assert !(v isa Thunk) "Cannot use `Thunk`s in `@spawn`/`spawn`" if v isa DTask task = v - if istaskstarted(task) + if task.stub !== nothing + # No thunk exists here: the placeholder result is the argument + arg.value = task.stub + elseif istaskstarted(task) #=FIXME:UNIQUE=# arg.value = Sch.ThunkID(Int(task.uid), task.thunk_ref) end @@ -407,7 +416,9 @@ function eager_process_elem_submission_to_local(arg::TypedArgument{T}) where T @assert !(T <: Thunk) "Cannot use `Thunk`s in `@spawn`/`spawn`" if T <: DTask task = value(arg)::DTask - if istaskstarted(task) + if task.stub !== nothing + return TypedArgument(arg.pos, task.stub) + elseif istaskstarted(task) #=FIXME:UNIQUE=# tid = Sch.ThunkID(Int(task.uid), task.thunk_ref) # Preserve the argument position by re-wrapping in a TypedArgument; @@ -531,26 +542,93 @@ arg_chunktypes(fargs::Vector) = ntuple(i->chunktype(value(fargs[i+1])), length(fargs)-1) function eager_spawn(spec::DTaskSpec) + # A reused/copied Options must not inherit another task's failure lifetime. + spec.options._owner_elision = nothing # Generate new unlaunched DTask - uid = eager_next_id() future = ThunkFuture() metadata = DTaskMetadata(spec) + # Metadata may invoke user hooks. Finish it before taking the id, so a + # reentrant root submission cannot advance an acceleration's registration + # watermark past a task whose state has not been published yet. + uid = eager_next_id() # Propagate inferred return type to options if isconcretetype(metadata.return_type) spec.options.return_type = metadata.return_type end - return DTask(uid, future, metadata) + task = DTask(uid, future, metadata) + accel = spec.options.acceleration + accel === nothing || prepare_owner_elision!(accel, spec, task) + return task end +prepare_owner_elision!(::Acceleration, spec, task) = nothing + chunktype(t::DTask) = t.metadata.return_type +const ELIDE_FOREIGN_TASKS = Ref{Bool}(false) + +""" + elide_foreign_tasks!(on::Bool=true) + +Switch owner elision on or off for this process (off by default); see +[`elide_task!`](@ref). The flag is read each time a task is submitted, so it can be +changed at run time. Under SPMD every rank must call it with the same value at the +same point of the program. + +The result protocol is captured when the task is submitted. Changing the flag +waits until previously submitted tasks finish, and must not be called from +inside a task. Existing task and result handles continue to report failures +after the flag is changed. +""" +function elide_foreign_tasks!(on::Bool=true) + if ELIDE_FOREIGN_TASKS[] != on + in_task() && throw(ArgumentError("`elide_foreign_tasks!` cannot change the flag from inside a task")) + state = Sch.EAGER_STATE[] + if state !== nothing + # N.B. The long-lived root thunk of the eager scheduler holds one credit + while state.running_count[] > 1 + sleep(0.001) + end + end + ELIDE_FOREIGN_TASKS[] = on + end + return on +end + +""" + elide_task!(accel::Acceleration, spec::DTaskSpec, task::DTask) -> Bool + +Give the acceleration the chance to complete `task` without building, scheduling +or running a `Thunk` for it, because this process takes no part in executing it +and nothing it does can depend on the outcome. When it returns `true`, `task` +must be complete: its future filled and `task.stub` set to a placeholder +result that downstream submissions can use in place of the task. The default +elides nothing. +""" +elide_task!(::Acceleration, spec, task) = false + # N.B. `DTaskPair.spec` is abstractly typed, so every use of it directly (the # `is_typed(spec)` and `spec.fargs` / `spec.options` property calls) is a dynamic # dispatch that recomputes the spec's type parameters; about half a dozen per task # made the call sites ~90 % of this function's samples. One dispatch here, onto the # concrete spec type, leaves everything below statically typed. eager_launch!(pair::DTaskPair) = _eager_launch!(pair.spec, pair.task) +function _try_owner_elision!(spec::DTaskSpec, task::DTask) + # Tasks this process only has to account for (never run or source data for) + # skip the thunk entirely + if task.owner_elision !== nothing && !Dagger.in_task() + # The first real submission starts the eager scheduler, which takes a task + # id of its own. Elision must not change which process consumes which + # ids (they feed the uniform MPI tags), so start it here, at the same + # point in the id sequence, whether or not this task is elided. + Sch.EAGER_STATE[] === nothing && myid() == 1 && Sch.init_eager() + accel = spec.options.acceleration + accel !== nothing && elide_task!(accel, spec, task) && return true + end + return false +end function _eager_launch!(spec::DTaskSpec, task::DTask) + _try_owner_elision!(spec, task) && return # Assign a name, if specified eager_assign_name!(spec, task) @@ -598,6 +676,22 @@ function _submission_fargs!(spec::DTaskSpec) end end function eager_launch!(pairs::Vector{DTaskPair}) + for pair in pairs + if pair.task.owner_elision !== nothing + # Examine in submission order: a later task can use the placeholder + # just produced for an earlier task in this same batch. + remaining = DTaskPair[] + sizehint!(remaining, length(pairs)) + for candidate in pairs + _try_owner_elision!(candidate.spec, candidate.task) || push!(remaining, candidate) + end + isempty(remaining) || _eager_launch_batch!(remaining) + return + end + end + _eager_launch_batch!(pairs) +end +function _eager_launch_batch!(pairs::Vector{DTaskPair}) ntasks = length(pairs) # Assign a name, if specified diff --git a/src/task-tls.jl b/src/task-tls.jl index 69111ac7a..0ee120eb3 100644 --- a/src/task-tls.jl +++ b/src/task-tls.jl @@ -78,7 +78,10 @@ task_id() = get_tls().sch_handle.thunk_id.id Get the current processor executing the current [`DTask`](@ref). """ -task_processor() = get_tls().processor +task_processor() = task_processor(get_tls().processor) +# Accelerations with migratable CPU tasks can report the thread executing +# this query rather than the processor selected before the task was launched. +task_processor(proc::Processor) = proc @deprecate(thunk_processor(), task_processor()) """ diff --git a/src/threadproc.jl b/src/threadproc.jl index 13955ca45..1a712bb43 100644 --- a/src/threadproc.jl +++ b/src/threadproc.jl @@ -2,11 +2,51 @@ ThreadProc <: Processor Julia CPU (OS) thread, identified by Julia thread ID. + +Dagger creates one `ThreadProc` per thread of Julia's default thread pool, and +none for interactive threads (see `Dagger.default_pool_tids`). """ struct ThreadProc <: Processor owner::Int tid::Int end + +""" + default_pool_tids() -> Vector{Int} + +The IDs of this process's default-pool threads: the threads that Dagger creates +a [`ThreadProc`](@ref) for, and so the only threads that run Dagger tasks. + +Interactive threads are left out. Julia starts one by default since 1.12 (and +with `julia -t N,M` before that), and numbers them first, so thread 1 is then +interactive and the default pool is threads `2:N+1`; `Threads.nthreads()` counts +only the default pool. The main task (and the REPL) run on thread 1 in that +case. Julia reserves interactive threads for short, latency-sensitive work, and +running arbitrary tasks there would make the REPL, and anything else that +expects that thread to respond quickly, wait behind them. +""" +default_pool_tids() = Threads.threadpooltids(:default) + +# `first(default_pool_tids())` without allocating a vector: Julia numbers the +# interactive pool first, so the default pool starts right after it (this is +# how `Threads.threadpooltids` itself computes the range). +first_default_tid() = Threads.threadpoolsize(:interactive) + 1 + +# Worker `pid`'s lowest-numbered CPU thread processor, for code that means "the +# worker's first thread". Not `ThreadProc(pid, 1)`: when the worker has an +# interactive thread, that is thread 1, and Dagger has no processor for it. +function first_thread_proc(pid::Int=myid()) + first_proc = nothing + for proc in get_processors(OSProc(pid)) + proc isa ThreadProc || continue + if first_proc === nothing || proc.tid < first_proc.tid + first_proc = proc + end + end + first_proc === nothing && error("Worker $pid has no CPU thread processors") + return first_proc::ThreadProc +end + iscompatible(proc::ThreadProc, opts, f, args...) = true iscompatible_func(proc::ThreadProc, opts, f) = true iscompatible_arg(proc::ThreadProc, opts, x) = true @@ -16,15 +56,7 @@ function execute!(proc::ThreadProc, @nospecialize(f), @nospecialize(args...); @n # Already pinned to this processor's thread (the normal case when the # scheduler runs us on a pooled, pinned task): run inline instead of # spawning and fetching a second Task. TLS is already ours. - if task_logging_enabled() - TimespanLogging.prof_task_put!(tls.sch_handle.thunk_id.id) - end - try - return @invokelatest f(args...; kwargs...) - catch err - err isa InterruptException && rethrow() - rethrow(CapturedException(err, catch_backtrace())) - end + return execute_thread_function(f, args...; kwargs...) end # FIXME: Use return type of the call to specialize container result = Ref{Any}() @@ -58,3 +90,17 @@ default_enabled(proc::ThreadProc) = true short_name(proc::ThreadProc) = "W: $(proc.owner), TID: $(proc.tid)" # TODO: ThreadGroupProc? + +# Shared by the pinned CPU fast path and accelerations that allow execution +# on whichever default-pool thread is currently running the scheduler task. +function execute_thread_function(@nospecialize(f), @nospecialize(args...); @nospecialize(kwargs...)) + if task_logging_enabled() + TimespanLogging.prof_task_put!(get_tls().sch_handle.thunk_id.id) + end + try + return @invokelatest f(args...; kwargs...) + catch err + err isa InterruptException && rethrow() + rethrow(CapturedException(err, catch_backtrace())) + end +end diff --git a/src/utils/reuse.jl b/src/utils/reuse.jl index 25c309347..6306953bf 100644 --- a/src/utils/reuse.jl +++ b/src/utils/reuse.jl @@ -633,6 +633,7 @@ function initialize_reusable_task_slot!(cache::ReusableTaskCache, idx::Int) end function reusable_task_loop(chan::Channel{Any}, ready::Threads.Atomic{Bool}) r = rand(1:128) + initially_migratable = !current_task().sticky while true f = try take!(chan) @@ -648,6 +649,15 @@ function reusable_task_loop(chan::Channel{Any}, ready::Threads.Atomic{Bool}) catch err @error "[$r] Error in reusable task" exception=(err, catch_backtrace()) end + if initially_migratable && current_task().sticky + # Scheduling @async can pin a formerly migratable slot. Do not + # unset sticky while its children may still need that affinity: + # retire it, and publish the closed channel before releasing the + # slot so the next dispatch creates a fresh migratable task. + close(chan) + Threads.atomic_xchg!(ready, true) + return + end Threads.atomic_xchg!(ready, true) end end @@ -661,7 +671,11 @@ function (cache::ReusableTaskCache)(f, name::String, register=nothing) idx = findfirst(getindex, cache.ready) if idx !== nothing @assert Threads.atomic_xchg!(cache.ready[idx], false) - t = isassigned(cache.tasks, idx) ? cache.tasks[idx] : initialize_reusable_task_slot!(cache, idx) + t = if isassigned(cache.tasks, idx) && isopen(cache.chans[idx]) + cache.tasks[idx] + else + initialize_reusable_task_slot!(cache, idx) + end register === nothing || register(t) put!(cache.chans[idx], f) # N.B. No errormonitor_tracked_set! here: pooled tasks are registered diff --git a/test/allocations.jl b/test/allocations.jl index 5b70e402b..e009d40b3 100644 --- a/test/allocations.jl +++ b/test/allocations.jl @@ -124,8 +124,9 @@ function alloc_bound(name) bytes=ceil(Int, b.bytes * ALLOC_BOUND_MULTIPLIER)) end -# Pin all work to one processor so results are topology-independent. -const ALLOC_TEST_SCOPE = Dagger.scope(worker=1, thread=1) +# Pin all work to one processor so results are topology-independent. (The +# first default-pool thread: thread 1 is interactive whenever one exists.) +const ALLOC_TEST_SCOPE = Dagger.scope(worker=1, thread=Dagger.first_default_tid()) fmt_bytes(b) = b < 1024 ? "$(b) B" : b < 1024^2 ? string(round(b / 1024; digits=1), " KiB") : diff --git a/test/array/allocation.jl b/test/array/allocation.jl index 4548f3ed1..645b76a75 100644 --- a/test/array/allocation.jl +++ b/test/array/allocation.jl @@ -471,8 +471,12 @@ test_assignment_strategy(:cyclicrow, get_cyclicrow_procgrid) test_assignment_strategy(:cycliccol, get_cycliccol_procgrid) @testset "OSProc ID Array Assignment (AbstractArray{<:Int, N})" begin + # Each worker's first CPU thread, which is not thread 1 when the worker + # has an interactive thread + first_tid(proc) = proc == myid() ? first(Threads.threadpooltids(:default)) : + remotecall_fetch(() -> first(Threads.threadpooltids(:default)), proc) function get_random_threadprocs(proc_ids) - [ThreadProc(proc, 1) for proc in proc_ids] + [ThreadProc(proc, first_tid(proc)) for proc in proc_ids] end rand_osproc_ids_A = rand(procs(), 3, 2, 2) diff --git a/test/datadeps.jl b/test/datadeps.jl index a97720a5e..05daeb02a 100644 --- a/test/datadeps.jl +++ b/test/datadeps.jl @@ -1054,10 +1054,12 @@ function test_datadeps(;args_chunks::Bool, for proc in exec_procs @test proc in scope_procs end - for proc in scope_procs - proc == Dagger.ThreadProc(1, 1) && continue - @test proc in exec_procs - end + # The unpinned tasks may all finish on one eligible processor. Exercise + # each processor in the outer scope with an explicitly placed task. + scoped_procs = fetch.(Dagger.spawn_datadeps() do + [Dagger.@spawn scope=ExactScope(proc) Dagger.task_processor() for proc in scope_procs] + end) + @test scoped_procs == scope_procs # Inner Scope @test_throws Dagger.Sch.SchedulingException Dagger.spawn_datadeps() do @@ -1165,7 +1167,7 @@ end for nt in (1, 2) if nprocs() >= nw && Threads.nthreads() >= nt @testset "$nw Workers, $nt Threads" begin - Dagger.with_options(;scope=Dagger.scope(workers=1:nw, threads=1:nt)) do + Dagger.with_options(;scope=Dagger.scope(workers=1:nw, threads=Dagger.default_pool_tids()[1:nt])) do test_datadeps(;args_chunks, args_thunks, args_loc) end end diff --git a/test/extlang/python.jl b/test/extlang/python.jl index 64e6d62c2..9257b93b2 100644 --- a/test/extlang/python.jl +++ b/test/extlang/python.jl @@ -27,3 +27,25 @@ Dagger.cancel!(;halt_sch=true) @test result isa Py @test pyconvert(Array, result) == [9, 12, 15] end + +@testset "Python execution from CPU work stealing" begin + # The scheduler may steal Python work onto a CPU processor even though + # direct Python placement prefers PythonProcessor. Exercise that dispatch + # from a real Dagger task, with its normal TLS and profiling state. + function execute_python_on_cpu(f, args...; kwargs...) + Dagger.execute!(Dagger.task_processor(), f, args...; kwargs...) + end + cpu_procs = [p for p in Dagger.get_processors(Dagger.OSProc()) if p isa Dagger.ThreadProc] + builtins = pyimport("builtins") + for proc in cpu_procs + result = fetch(Dagger.@spawn scope=Dagger.ExactScope(proc) execute_python_on_cpu(builtins.sum, [1, 2, 3])) + @test result isa Py + @test pyconvert(Int, result) == 6 + result = fetch(Dagger.@spawn scope=Dagger.ExactScope(proc) execute_python_on_cpu(builtins.sorted, [1, 3, 2]; reverse=true)) + @test pyconvert(String, pyrepr(result)) == "[3, 2, 1]" + @test_throws Dagger.DTaskFailedException fetch(Dagger.@spawn scope=Dagger.ExactScope(proc) execute_python_on_cpu(builtins.int, "invalid integer")) + end + tasks = [Dagger.@spawn scope=Dagger.ExactScope(cpu_procs[mod1(i, length(cpu_procs))]) execute_python_on_cpu(builtins.sum, [i, i + 1]) for i in 1:24] + @test pyconvert.(Int, fetch.(tasks)) == [2i + 1 for i in 1:24] + @test_throws Dagger.DTaskFailedException fetch(Dagger.@spawn builtins.int("invalid integer")) +end diff --git a/test/gpu.jl b/test/gpu.jl index 94f81e1d8..59e36a458 100644 --- a/test/gpu.jl +++ b/test/gpu.jl @@ -181,7 +181,7 @@ end A = rand(Float64, 128) B = zeros(Float64, 128) - Dagger.with_options(scope=Dagger.scope(worker=1,thread=1)) do + Dagger.with_options(scope=Dagger.scope(worker=1,thread=Dagger.first_default_tid())) do fetch(Dagger.@spawn Kernel(copy_kernel)(B, A; ndrange=length(A))) Dagger.gpu_synchronize(:CPU) end diff --git a/test/mpi/cpu.jl b/test/mpi/cpu.jl index e950e75de..97fa983f9 100644 --- a/test/mpi/cpu.jl +++ b/test/mpi/cpu.jl @@ -61,6 +61,30 @@ proc_for_rank(r) = first(filter(p->p.rank == r, mpi_procs())) space_for_rank(r) = MPIExt.MPIMemorySpace(Dagger.CPURAMMemorySpace(1), comm, r) rank_scope(r) = Dagger.ExactScope(proc_for_rank(r)) +struct SpectatorThreadCopy end +const spectator_copy_tid = Ref(0) +function Dagger.move!(::SpectatorThreadCopy, to_space::MPIExt.MPIMemorySpace, + from_space::MPIExt.MPIMemorySpace, to::Dagger.Chunk, from::Dagger.Chunk) + spectator_copy_tid[] = Threads.threadid() + return Dagger.move!(identity, to_space, from_space, to, from) +end + +@testset "MPI copy spectators use the default thread pool" begin + if nranks >= 3 + src_space, dst_space = space_for_rank(0), space_for_rank(1) + payload = collect(1:4) + src = Dagger.tochunk(payload, proc_for_rank(0), src_space) + dst = Dagger.tochunk(zeros(Int, 4), proc_for_rank(1), dst_space) + copy_task = Dagger.@spawn scope=rank_scope(1) meta=true Dagger.move!( + SpectatorThreadCopy(), dst_space, src_space, dst, src) + wait(copy_task) + if rank >= 2 + @test spectator_copy_tid[] == first(Threads.threadpooltids(:default)) + end + @test fetch(dst) == payload + end +end + # Rank pairs for slot tests (mirrors Distributed's worker pairs), including a # same-rank pair to check that origin slots alias the original data const rank_pairs = if nranks >= 3 @@ -172,6 +196,10 @@ end include("spawn.jl") include("noaliasing_args.jl") +include("free_threads.jl") +include("relay.jl") +include("elide.jl") +include("skip_tasks.jl") @testset "Datadeps" begin diff --git a/test/mpi/elide.jl b/test/mpi/elide.jl new file mode 100644 index 000000000..1644ed846 --- /dev/null +++ b/test/mpi/elide.jl @@ -0,0 +1,505 @@ +# Owner elision (`Dagger.elide_foreign_tasks!`): a rank that neither runs a task nor +# owns its data builds no thunk for it. The program must still be indistinguishable: +# same task ids on every rank, same results, same behaviour of later SPMD work. +elide_inc(x::Int) = x + 1 # concrete, cannot throw: elidable +elide_add(a::Int, b::Int) = a + b +elide_throws(x::Int) = x > 0 ? error("elide_throws") : x # may throw, concrete Int +elide_len(x::Vector{Int}) = length(x) # concrete, cannot throw +elide_blocksum(x::Matrix{Float64}) = sum(x) +elide_slow_throws(x::Int) = (sleep(0.5); x > 0 ? error("elide_slow_throws") : x) +elide_rank() = MPI.Comm_rank(MPI.COMM_WORLD) +const ELIDE_CHECKPOINT_HITS = Threads.Atomic{Int}(0) +elide_checkpoint_hit(node, result) = (Threads.atomic_add!(ELIDE_CHECKPOINT_HITS, 1); nothing) +elide_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) # concrete, cannot be proven not to throw +elide_filtered_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) +Dagger.iscompatible_func(p::MPIExt.MPIProcessor{Dagger.ThreadProc}, ::Dagger.Options, ::Type{typeof(elide_filtered_where)}) = + p.innerProc.tid == last(Dagger.default_pool_tids()) +elide_default_target() = 42 +elide_option_scope_where() = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid()) +Dagger.iscompatible_func(p::MPIExt.MPIProcessor{Dagger.ThreadProc}, opts::Dagger.Options, + ::Type{typeof(elide_option_scope_where)}) = + opts.compute_scope isa Dagger.UnionScope && p.innerProc.tid == last(Dagger.default_pool_tids()) +elide_allow_last(p) = p.innerProc isa Dagger.ThreadProc && p.innerProc.tid == last(Dagger.default_pool_tids()) +Dagger.default_option(::Val{:proclist}, ::Type{typeof(elide_default_target)}) = elide_allow_last + +function elide_orphan_state() + state = MPIExt.OwnerElisionState(UInt32(0), 0, nothing) + @lock MPIExt.OWNER_ELISION_LOCK MPIExt.owner_elision_register!(state) + MPIExt.owner_elision_deliver!(0, UInt32(0), ErrorException("orphan elision failure")) + return WeakRef(state) +end +struct ElideMoveFailure end +Dagger.move(::MPIExt.MPIProcessor, ::MPIExt.MPIProcessor, ::ElideMoveFailure) = + (sleep(0.1); error("expected owner-elision source transfer failure")) +elide_consume(::ElideMoveFailure) = 1 +elide_consume(::ElideMoveFailure, b::Vector{UInt8}) = length(b) +elide_sum_bytes(a::Vector{UInt8}, b::Vector{UInt8}, c::Vector{UInt8}) = Int(sum(a) + sum(b) + sum(c)) + +# Notify the real MPI peer at cancellation, without timing/JIT assumptions. +# Completion and buffer ownership are still those of an actual rendezvous send. +mutable struct ElideCleanupRequest <: MPI.AbstractRequest + request::MPI.Request + comm::MPI.Comm + signal_tag::UInt32 + signalled::Bool +end +MPI.isnull(req::ElideCleanupRequest) = MPI.isnull(req.request) +MPI.Test(req::ElideCleanupRequest) = MPI.Test(req.request) +MPI.Test(req::ElideCleanupRequest, ::Type{MPI.Status}) = MPI.Test(req.request, MPI.Status) +function MPI.Cancel!(req::ElideCleanupRequest) + req.signalled = true + MPI.send(true, req.comm; dest=1, tag=req.signal_tag) + MPI.Cancel!(req.request) +end + +@testset "Owner elision" begin + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) + pinned(r) = Dagger.ExactScope(last(filter(p -> p.rank == r, cpus))) + # Uniformity checks are collective over all ranks and so disable elision + Dagger.check_uniformity!(false) + # The switch is off by default and read at run time: with it off nothing is elided + @testset "switch off: nothing is elided" begin + @test !Dagger.ELIDE_FOREIGN_TASKS[] + for target in 0:nranks-1 + t = Dagger.@spawn scope=pinned(target) elide_inc(41) + @test fetch(t) == 42 + @test t.stub === nothing + @test t.owner < 0 + end + end + Dagger.elide_foreign_tasks!(true) + try + @testset "pinned tasks: results, stubs, uniform ids" begin + for target in 0:nranks-1 + t = Dagger.@spawn scope=pinned(target) elide_inc(41) + wait(t) + @test (t.stub !== nothing) == (rank != target) + @test t.owner == target + @test fetch(t) == 42 + @test allequal(MPI.Allgather(Int(t.uid), comm)) + # the placeholder and the real chunk agree on type and space + chunk = fetch(t; raw=true) + @test chunk.chunktype === Int + @test allequal(MPI.Allgather(hash((chunk.handle.rank, chunk.handle.id, chunk.chunktype)), comm)) + end + end + + @testset "rank-level scope: the scheduler picks the thread" begin + # `scope(mpi_rank=r)` names a rank, not a thread; the rank is all a spectator needs + for target in 0:nranks-1 + t = Dagger.@spawn scope=Dagger.scope(mpi_rank=target) elide_inc(1) + wait(t) + @test (t.stub !== nothing) == (rank != target) + @test t.owner == target + @test fetch(t) == 2 + @test allequal(MPI.Allgather(Int(t.uid), comm)) + chunk = fetch(t; raw=true) + @test chunk.handle.rank == target + @test allequal(MPI.Allgather(hash((chunk.handle.rank, chunk.handle.id, chunk.chunktype)), comm)) + end + # one scope object shared by many tasks (a `with_options` block): the owner spreads them over its threads + target = nranks - 1 + tasks = Dagger.with_options(; scope=Dagger.scope(mpi_rank=target)) do + [Dagger.@spawn(elide_where()) for _ in 1:16] + end + where = fetch.(tasks) + @test all(w -> w[1] == target, where) + @test length(unique(last.(where))) >= min(2, Threads.nthreads()) + @test count(t -> t.stub !== nothing, tasks) == (rank == target ? 0 : 16) + # A spectator's placeholder names the processor the owner ran the task on (it used to name a fixed + # member of the scope, so the ranks disagreed on `chunk.processor`) + stamped = [(p.rank, p.innerProc.tid) for p in (fetch(t; raw=true).processor for t in tasks)] + @test allequal(MPI.Allgather(hash(stamped), comm)) + # Predicates may inspect user options. Proven logical placement + # must not rewrite those options before the scheduler checks them. + option_tasks = [Dagger.@spawn(scope=Dagger.scope(mpi_rank=target), elide_option_scope_where()) for _ in 1:8] + @test all(w -> first(w) == target, fetch.(option_tasks)) + @test all(t -> fetch(t; raw=true).processor.innerProc.tid == last(Dagger.default_pool_tids()), option_tasks) + # a chain across two rank-level scopes, and a failure + a = Dagger.@spawn scope=Dagger.scope(mpi_rank=0) elide_inc(1) + b = Dagger.@spawn scope=Dagger.scope(mpi_rank=nranks-1) elide_add(a, 10) + @test fetch(b) == 12 + bad = Dagger.@spawn scope=Dagger.scope(mpi_rank=0) elide_throws(1) + @test (bad.stub !== nothing) == (rank != 0) + @test_throws Exception fetch(bad) + dep = Dagger.@spawn scope=Dagger.scope(mpi_rank=nranks-1) elide_inc(bad) + @test_throws Exception fetch(dep) + # What a rank scope names is cached under a key made from its contents and confirmed with `===`: two equal scopes + # built separately resolve to the same rank and share one entry, scopes of different ranks never share an + # answer, and a scope that is dropped and replaced by another one cannot return the old answer. + for target in 0:nranks-1 + s1 = Dagger.scope(mpi_rank=target); s2 = Dagger.scope(mpi_rank=target) + @test s1 == s2 + for s in (s1, s2, s1, s2) + o = Dagger.Options(; scope=s) + p = MPIExt.mpi_scope_processor(o) + @test p isa MPIExt.MPIProcessor && p.rank == target + end + end + for round in 1:20, target in 0:nranks-1 + o = Dagger.Options(; scope=Dagger.scope(mpi_rank=target)) # a new scope object every time + @test MPIExt.mpi_scope_processor(o).rank == target + GC.gc(false) + end + # equal scope objects rebuilt on the way to the planner must not each get a cache entry + MPIExt.mpi_union_scope_processor(Dagger.scope(mpi_rank=rank)) + n1 = length(MPIExt.MPI_UNION_SCOPE_CACHE.table) + for _ in 1:20 + MPIExt.mpi_union_scope_processor(Dagger.scope(mpi_rank=rank)) + end + @test length(MPIExt.MPI_UNION_SCOPE_CACHE.table) == n1 + # several ranks allowed: the rank is the scheduler's choice, nothing is elided + multi = Dagger.@spawn scope=Dagger.scope(mpi_ranks=:) elide_inc(1) + @test multi.stub === nothing + @test fetch(multi) == 2 + end + + @testset "tasks without a scope: placed at spawn" begin + # The owner follows the deterministic placement rule and is decided when the + # task is created, so every other rank can elide it. The scheduler must + # then run it exactly where the rule said. + n = nranks * Threads.nthreads() + tasks = [Dagger.@spawn(elide_inc(i)) for i in 1:2n] + @test fetch.(tasks) == [i + 1 for i in 1:2n] + @test all(t -> t.owner >= 0, tasks) + @test all(t -> fetch(t; raw=true).handle.rank == t.owner, tasks) + @test all(t -> allequal(MPI.Allgather(Int(t.uid), comm)), tasks[1:4]) + @test count(t -> t.stub !== nothing, tasks) == count(t -> t.owner != rank, tasks) + @test all(r -> any(t -> t.owner == r, tasks), 0:nranks-1) # round robin reaches every rank + # data affinity: a task that reads an MPI chunk runs on the chunk's rank + x = Dagger.tochunk(10, proc_for_rank(0), space_for_rank(0)) + y = Dagger.@spawn elide_inc(x) + @test y.owner == 0 + @test fetch(y) == 11 + @test (y.stub !== nothing) == (rank != 0) + # a chain without scopes stays on one rank, and a scoped producer is followed + u1 = Dagger.@spawn scope=pinned(nranks-1) elide_inc(1) + u2 = Dagger.@spawn elide_inc(u1) + u3 = Dagger.@spawn elide_add(u2, u1) + @test u2.owner == nranks - 1 && u3.owner == nranks - 1 + @test fetch(u3) == 3 + 2 + # an argument whose owner is unknown at spawn time: left to the scheduler + lazy = Dagger.@spawn scope=Dagger.scope(mpi_ranks=:) elide_inc(1) + z = Dagger.@spawn elide_inc(lazy) + @test lazy.stub === nothing && z.stub === nothing + @test fetch(z) == 3 + # a failing task without a scope: every rank sees an error and none hangs + bad = Dagger.@spawn elide_throws(1) + @test_throws Exception fetch(bad) + dep = Dagger.@spawn elide_inc(bad) + @test_throws Exception fetch(dep) + end + + @testset "chunk arguments with a scope restriction (as a DArray block has)" begin + # A chunk owned by `target` whose scope names that rank: a rank that neither runs the task nor + # owns the chunk elides the task. The restriction only matters if it contradicts the task's scope. + # N.B. `tochunk(x, proc, scope)` would place the chunk on rank 0 (the owner of plain values), so the memory + # space is given as well. + target = nranks - 1 + data = fill(5, 4) + restricted = Dagger.tochunk(data, proc_for_rank(target), space_for_rank(target), Dagger.scope(mpi_rank=target)) + t = Dagger.@spawn scope=Dagger.scope(mpi_rank=target) elide_len(restricted) + wait(t) + @test (t.stub !== nothing) == (rank != target) + @test fetch(t) == 4 + @test allequal(MPI.Allgather(Int(t.uid), comm)) + # ... and when the chunk is also an argument of a task pinned to one processor of that rank + t2 = Dagger.@spawn scope=pinned(target) elide_len(restricted) + wait(t2) + @test (t2.stub !== nothing) == (rank != target) + @test fetch(t2) == 4 + if nranks > 1 + # A scope that contradicts the task's is not elided: the scheduler of the owner fails the task + other = (target + 1) % nranks + clash = Dagger.tochunk(data, proc_for_rank(other), space_for_rank(other), Dagger.scope(mpi_rank=other)) + t3 = Dagger.@spawn scope=Dagger.scope(mpi_rank=target) elide_len(clash) + @test t3.stub === nothing + @test_throws Exception fetch(t3) + @test allequal(MPI.Allgather(Int(t3.uid), comm)) + end + end + + @testset "DArray blocks: where they live is known when the task that reads one is spawned" begin + # The blocks of an array are tasks of a Datadeps region (not elidable themselves), but their placement is + # the same grid on every rank: the consumers of a block are planned in full only by ranks that take part + A = zeros(Blocks(2, 2), Float64, 2 * nranks, 2) + blocks = vec(A.chunks) + placed = [b.placed for b in blocks] + @test all(>=(0), placed) + held = [fetch(b; raw=true).handle.rank for b in blocks] + @test placed == held # what was recorded is where the block is + @test allequal(MPI.Allgather(hash(placed), comm)) + for (i, b) in enumerate(blocks) + o = placed[i] + t = Dagger.@spawn scope=Dagger.scope(mpi_rank=o) elide_blocksum(b) + wait(t) + @test (t.stub !== nothing) == (rank != o) # every other rank elides it + @test fetch(t) == 0.0 + @test allequal(MPI.Allgather(Int(t.uid), comm)) + end + if nranks >= 3 + # on another rank than the block's: the block's rank sends the data (takes part), a third rank elides + o = placed[1] + other = (o + 1) % nranks + t = Dagger.@spawn scope=Dagger.scope(mpi_rank=other) elide_blocksum(blocks[1]) + wait(t) + @test (t.stub !== nothing) == (rank != o && rank != other) # every rank outside the transfer elides + @test fetch(t) == 0.0 + @test allequal(MPI.Allgather(Int(t.uid), comm)) + end + end + + @testset "dependent chains" begin + # a chain on one rank, then a consumer on another + a = Dagger.@spawn scope=pinned(0) elide_inc(1) + b = Dagger.@spawn scope=pinned(0) elide_inc(a) + c = Dagger.@spawn scope=pinned(nranks-1) elide_add(b, a) + @test fetch(c) == 3 + 2 + @test (a.stub !== nothing) == (rank != 0) + @test (c.stub !== nothing) == (rank != nranks - 1 && rank != 0) # rank 0 owns a and b: it sends them + # many tasks across all ranks + tasks = [Dagger.@spawn(scope=pinned(i % nranks), elide_inc(i)) for i in 1:4nranks] + @test fetch.(tasks) == [i + 1 for i in 1:4nranks] + @test count(t -> t.stub !== nothing, tasks) == 4nranks - 4 + end + + @testset "tasks that must not be elided" begin + # a rank that owns an argument takes part + x = Dagger.tochunk(10, proc_for_rank(0), space_for_rank(0)) + t = Dagger.@spawn scope=pinned(nranks-1) elide_inc(x) + @test (t.stub !== nothing) == (rank != 0 && rank != nranks - 1) + @test fetch(t) == 11 + # a tagged task keeps the status broadcast + v = Dagger.@spawn scope=pinned(0) tag=UInt32(12345) elide_inc(1) + @test v.stub === nothing + @test fetch(v) == 2 + end + + @testset "checkpoint callbacks still run on every rank" begin + for enabled in (false, true) + Dagger.elide_foreign_tasks!(enabled) + before = ELIDE_CHECKPOINT_HITS[] + t = Dagger.@spawn scope=pinned(nranks-1) checkpoint=elide_checkpoint_hit elide_inc(1) + @test fetch(t) == 2 + @test t.stub === nothing + @test t.owner < 0 + hits = ELIDE_CHECKPOINT_HITS[] - before + @test hits == 1 + @test all(==(1), MPI.Allgather(hits, comm)) + end + end + + @testset "tasks that may throw" begin + # success: elided like any other, nobody waits for a status + ok = Dagger.@spawn scope=pinned(0) elide_throws(0) + @test (ok.stub !== nothing) == (rank != 0) + @test fetch(ok) == 0 + # failure: every rank sees an error, none hangs + bad = Dagger.@spawn scope=pinned(0) elide_throws(1) + @test (bad.stub !== nothing) == (rank != 0) + @test_throws Exception fetch(bad) + # ... and so does a task that consumes the failed task's result, wherever it runs + for target in 0:nranks-1 + dep = Dagger.@spawn scope=pinned(target) elide_inc(bad) + @test_throws Exception fetch(dep) + end + # a failure far from the data: the consumer's own rank learns of it on the move + far = Dagger.@spawn scope=pinned(nranks-1) elide_add(bad, 1) + @test_throws Exception fetch(far) + end + + @testset "changing the switch waits for the tasks in flight" begin + # Whether a task reports only failures is decided when it runs: a task submitted with the + # switch on must not run with it off (the ranks that elided it would wait for a status). + bad = Dagger.@spawn scope=pinned(0) elide_slow_throws(1) + Dagger.elide_foreign_tasks!(false) + @test isready(bad) # the owner's task was waited for + @test_throws Exception fetch(bad) # old handles work while the switch stays off + @test_throws Exception fetch(bad) # failure is retained for repeated fetches + Dagger.check_uniformity!(true) + @test fetch(Dagger.@spawn scope=pinned(0) elide_inc(1)) == 2 + Dagger.check_uniformity!(false) + Dagger.elide_foreign_tasks!(true) + @test_throws Exception fetch(Dagger.@spawn scope=pinned(0) Dagger.elide_foreign_tasks!(false)) + end + + @testset "bulk submission keeps owner elision" begin + target = nranks - 1 + tasks = Dagger.spawn_bulk() do + a = Dagger.@spawn scope=pinned(target) elide_inc(1) + b = Dagger.@spawn scope=pinned(target) elide_inc(a) + (a, b) + end + @test fetch.(tasks) == (2, 3) + @test all(t -> (t.stub !== nothing) == (rank != target), tasks) + @test all(t -> t.owner == target, tasks) + end + + @testset "source argument failure reaches the owner" begin + if nranks > 1 + x = Dagger.tochunk(ElideMoveFailure(), proc_for_rank(0), space_for_rank(0)) + bad = Dagger.@spawn scope=pinned(nranks-1) elide_consume(x) + @test_throws Exception fetch(bad) + @test_throws Exception fetch(bad) + Dagger.check_uniformity!(true) + @test fetch(Dagger.@spawn scope=pinned(nranks-1) elide_inc(8)) == 9 + Dagger.check_uniformity!(false) + end + if nranks >= 3 + # Rank 2 can reach the second argument while the owner still + # waits for the failing first one. Wait for receiver readiness + # before posting this rendezvous payload, so rank 2 can abort. + x = Dagger.tochunk(ElideMoveFailure(), proc_for_rank(0), space_for_rank(0)) + big = Dagger.tochunk(zeros(UInt8, 8*1024*1024), proc_for_rank(2), space_for_rank(2)) + bad = Dagger.@spawn scope=pinned(1) elide_consume(x, big) + @test_throws Exception fetch(bad) + @test_throws Exception fetch(bad) + # Repeated arguments from one source receive distinct permits. + a = Dagger.tochunk(ones(UInt8, 1024*1024), proc_for_rank(0), space_for_rank(0)) + b = Dagger.tochunk(ones(UInt8, 1024*1024), proc_for_rank(2), space_for_rank(2)) + @test fetch(Dagger.@spawn scope=pinned(1) elide_sum_bytes(a, b, b)) == 3*1024*1024 + Dagger.check_uniformity!(true) + @test fetch(Dagger.@spawn scope=pinned(1) elide_inc(8)) == 9 + Dagger.check_uniformity!(false) + end + end + + @testset "active request retains its buffer through failure" begin + if nranks > 1 + tag = UInt32(MPI.tag_ub() - 2048) + if rank == 0 + request = MPI.Isend(zeros(UInt8, 8*1024*1024), comm; dest=1, tag) + req = ElideCleanupRequest(request, comm, tag + UInt32(1), false) + @test !MPI.Test(request) + poison = MPIExt.OwnerElisionState(tag, 0, ErrorException("expected active-request poison")) + try + @test_throws ErrorException MPIExt.with(MPIExt.POISON_TASK => poison) do + MPIExt.__wait_for_request(req, comm, 0, 1, tag, "cleanup test", "send") + end + @test MPI.isnull(request) + @test request.buffer === nothing + finally + # The pre-fix control also drains its native request, + # after recording the failed lifetime assertions. + if !req.signalled + MPI.send(true, comm; dest=1, tag=tag+UInt32(1)) + end + while !MPI.Test(request) + sleep(0.001) + end + MPI.send(true, comm; dest=1, tag=tag+UInt32(2)) + end + elseif rank == 1 + MPI.recv(comm; source=0, tag=tag+UInt32(1)) + while true + if MPI.Iprobe(comm; source=0, tag) + MPI.Recv!(zeros(UInt8, 8*1024*1024), comm; source=0, tag) + elseif MPI.Iprobe(comm; source=0, tag=tag+UInt32(2)) + MPI.recv(comm; source=0, tag=tag+UInt32(2)) + break + else + sleep(0.001) + end + end + end + barrier = MPI.Ibarrier(comm) + while !MPI.Test(barrier) + sleep(0.001) + end + end + end + + @testset "scoped placement respects processor eligibility" begin + target = nranks - 1 + tasks = [Dagger.@spawn(scope=Dagger.scope(mpi_rank=target), elide_filtered_where()) for _ in 1:8] + @test all(w -> first(w) == target, fetch.(tasks)) + stamped = [(p.rank, p.innerProc.tid) for p in (fetch(t; raw=true).processor for t in tasks)] + @test all(==((target, last(Dagger.default_pool_tids()))), stamped) + @test allequal(MPI.Allgather(hash(stamped), comm)) + # A default proclist is applied by the scheduler even when the + # caller did not supply it explicitly. Such tasks use full planning. + t = Dagger.@spawn scope=Dagger.scope(mpi_rank=target) elide_default_target() + @test t.stub === nothing + @test t.owner < 0 + @test fetch(t) == 42 + end + + @testset "failure lifetime follows handles" begin + target = nranks - 1 + # Earlier failures have warmed the error path. Let the owner submit + # first, so its failure arrives before peers register this task. + if rank != target + deadline = time() + 10 + while (@lock MPIExt.OWNER_ELISION_LOCK isempty(MPIExt.OWNER_ELISION_EARLY)) && time() < deadline + sleep(0.001) + end + @test (@lock MPIExt.OWNER_ELISION_LOCK !isempty(MPIExt.OWNER_ELISION_EARLY)) + end + bad = Dagger.@spawn scope=pinned(target) elide_throws(1) + @test_throws Exception fetch(bad) + @test_throws Exception fetch(bad) + state = bad.owner_elision + @test state isa MPIExt.OwnerElisionState + @test (@atomic state.error) !== nothing + # Serialization must reconnect a ref to the live local state rather + # than create a snapshot which misses a later failure notification. + io = IOBuffer() + MPIExt.Serialization.serialize(io, state) + seekstart(io) + @test MPIExt.Serialization.deserialize(io) === state + # A raw failed fetch consumes no generic fetch id on either rank. + raw = try + fetch(bad; raw=true) + catch + nothing + end + @test (raw === nothing) == (rank == target) + bad = nothing + GC.gc() + if rank != target + @test raw.handle.owner_elision === state + @test_throws Exception MPIExt.mpi_poisonable(raw.handle) do + MPIExt.mpi_check_poison() + end + @test_throws Exception MPIExt.mpi_poisonable(raw.handle) do + MPIExt.mpi_check_poison() + end + end + @test fetch(Dagger.@spawn scope=pinned(target) elide_inc(2)) == 3 + # Typed failures are not retained in the relay's ordinary FIFO. + relay = MPIExt.bcast_state_for(comm) + @test (@lock relay.cond !haskey(relay.slots, (target, state.tid))) + @test (@lock MPIExt.OWNER_ELISION_LOCK isempty(MPIExt.OWNER_ELISION_EARLY)) + orphan = elide_orphan_state() + for _ in 1:10 + GC.gc() + orphan.value === nothing && break + sleep(0.01) + end + @test orphan.value === nothing + end + + @testset "declared return type preserves failure-only protocol" begin + target = nranks - 1 + # Bottom inference must not switch a captured task back to the + # ordinary metadata FIFO: spectator tasks no longer consume it. + bad = Dagger.@spawn scope=pinned(target) return_type=Int error("declared failure") + @test bad.owner_elision isa MPIExt.OwnerElisionState + @test_throws Exception fetch(bad) + @test_throws Exception fetch(bad) + relay = MPIExt.bcast_state_for(comm) + @test (@lock relay.cond !haskey(relay.slots, (target, UInt32(bad.uid)))) + end + + @testset "later SPMD work is unaffected" begin + y = Dagger.@spawn scope=Dagger.scope(mpi_rank=nranks-1) fill(2.0, 8) + s = Dagger.@spawn scope=Dagger.scope(mpi_rank=0) sum(y) + @test fetch(s) == 16.0 + @test allequal(MPI.Allgather(Int(s.uid), comm)) + end + finally + Dagger.elide_foreign_tasks!(false) + Dagger.check_uniformity!(true) + end + MPI.Barrier(comm) +end diff --git a/test/mpi/elide_gpu.jl b/test/mpi/elide_gpu.jl new file mode 100644 index 000000000..3d328178f --- /dev/null +++ b/test/mpi/elide_gpu.jl @@ -0,0 +1,25 @@ +mpi_elide_gpu_scalar() = 7 +mpi_elide_gpu_host() = ones(Float32, 4) + +function test_owner_elision_gpu(gpu_scope) + old_uniform = Dagger.CHECK_UNIFORMITY[] + old_elision = Dagger.ELIDE_FOREIGN_TASKS[] + Dagger.check_uniformity!(false) + Dagger.elide_foreign_tasks!(true) + try + for (f, T) in ((mpi_elide_gpu_scalar, Int), (mpi_elide_gpu_host, Vector{Float32})) + task = Dagger.@spawn scope=gpu_scope return_type=T f() + @test task.stub === nothing + @test task.owner < 0 + chunk = fetch(task; raw=true) + @test chunk.chunktype === T + @test Dagger.memory_space(chunk).innerSpace isa Dagger.CPURAMMemorySpace + stamp = hash((chunk.chunktype, Dagger.memory_space(chunk))) + @test allequal(MPI.Allgather(stamp, MPI.COMM_WORLD)) + @test fetch(task) == (T === Int ? 7 : ones(Float32, 4)) + end + finally + Dagger.elide_foreign_tasks!(old_elision) + Dagger.check_uniformity!(old_uniform) + end +end diff --git a/test/mpi/free_threads.jl b/test/mpi/free_threads.jl new file mode 100644 index 000000000..3716f0804 --- /dev/null +++ b/test/mpi/free_threads.jl @@ -0,0 +1,302 @@ +# An MPI task whose thread nobody asked for runs on any free +# thread of its rank instead of waiting behind a busy one. +hog_busy(seconds::Float64) = (t0 = time(); while time() - t0 < seconds; end; 1) # does not yield +free_quick(x::Int) = x + 1 +free_where() = Threads.threadid() +free_reported_where() = (Threads.threadid(), Dagger.task_processor().innerProc.tid) +free_scope_value() = Dagger.UnionScope(Dagger.ProcessorTypeScope(Dagger.ThreadProc)) + +# Rank-local state is read inside the kernel, before MPI result delivery. A +# deadline only rescues a broken test; successful execution must beat release, +# not a wall-clock performance threshold. +const FREE_GATE_ENTERED = Threads.Atomic{Int}(0) +const FREE_GATE_ACTIVE = Threads.Atomic{Int}(0) +const FREE_GATE_RELEASE = Threads.Atomic{Bool}(true) +const FREE_GATE_COMPLETED = Threads.Atomic{Int}(0) +const FREE_GATE_WAIT_SECONDS = 30.0 + +function free_gated_hog() + start = time_ns() + Threads.atomic_add!(FREE_GATE_ACTIVE, 1) + Threads.atomic_add!(FREE_GATE_ENTERED, 1) + try + while !FREE_GATE_RELEASE[] && time_ns() - start < UInt64(90_000_000_000) + # Deliberately non-yielding: this is the occupied CPU thread. + end + return FREE_GATE_RELEASE[] + finally + Threads.atomic_sub!(FREE_GATE_ACTIVE, 1) + end +end + +function free_gated_quick(x::Int, busy::Int) + ran_while_busy = FREE_GATE_ACTIVE[] == busy && !FREE_GATE_RELEASE[] + tid = Threads.threadid() + Threads.atomic_add!(FREE_GATE_COMPLETED, 1) + return (x + 1, ran_while_busy, tid) +end + +function free_progress_case(scope, rank0, count::Int; expect_progress=true) + busy = length(rank0) - 1 + # Compile the exact kernels with an open gate before occupying any CPU. + FREE_GATE_RELEASE[] = true + foreach(fetch, [Dagger.@spawn(scope=Dagger.ExactScope(p), free_gated_hog()) for p in rank0]) + foreach(fetch, [Dagger.@spawn(scope=scope, free_gated_quick(i, busy)) for i in 1:count]) + FREE_GATE_ENTERED[] = 0 + FREE_GATE_ACTIVE[] = 0 + FREE_GATE_COMPLETED[] = 0 + FREE_GATE_RELEASE[] = false + hogs = Dagger.DTask[] + tasks = Dagger.DTask[] + entered_status = :not_checked + completed_status = :not_checked + local hog_results + try + for p in rank0[2:end] + push!(hogs, Dagger.@spawn(scope=Dagger.ExactScope(p), free_gated_hog())) + end + if rank == 0 + entered_status = timedwait(() -> FREE_GATE_ENTERED[] == busy, + FREE_GATE_WAIT_SECONDS; pollint=0.001) + end + for i in 1:count + push!(tasks, Dagger.@spawn(scope=scope, free_gated_quick(i, busy))) + end + if rank == 0 && expect_progress + completed_status = timedwait(() -> FREE_GATE_COMPLETED[] == count, + FREE_GATE_WAIT_SECONDS; pollint=0.001) + end + finally + # Even a failed progress assertion must release the occupied threads. + # Peers may already be fetching; that delivery latency is not asserted. + FREE_GATE_RELEASE[] = true + hog_results = fetch.(hogs) + end + # Failure reporting may compile and block; do it after releasing every CPU. + rank == 0 && @test entered_status === :ok + rank == 0 && expect_progress && @test completed_status === :ok + @test all(hog_results) + return fetch.(tasks) +end + +@testset "MPI CPU processor reports the executing thread" begin + tasks = [Dagger.@spawn free_reported_where() for _ in 1:32] + @test all(pair -> first(pair) == last(pair), fetch.(tasks)) +end + +@testset "Exact-scope union membership metadata" begin + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) + all_threads = Dagger.UnionScope(map(Dagger.ExactScope, cpus)) + members = MPIExt.mpi_exact_scope_members(all_threads) + @test members isa Dict{Dagger.AbstractScope,Nothing} + @test length(members) == length(cpus) + reordered = Dagger.UnionScope(reverse(map(Dagger.ExactScope, cpus))) + @test all_threads == reordered + @test hash(all_threads) == hash(reordered) + @test Dict(all_threads => true)[reordered] + fresh = Dagger.UnionScope(map(Dagger.ExactScope, cpus)) + @test fresh === all_threads + @test MPIExt.mpi_exact_scope_members(fresh) === members + accel = Dagger.current_acceleration() + procs = unique(Dagger.Processor[Dagger.get_parent(p) for p in cpus]) + a = Dagger.Sch.compatible_processors_cached(accel, all_threads, procs) + b = Dagger.Sch.compatible_processors_cached(accel, fresh, procs) + @test a === b + @test a == Set(cpus) + for proc in cpus + @test !MPIExt.mpi_thread_requested(proc, all_threads) + end + mixed = Dagger.UnionScope(Dagger.ExactScope(first(cpus)), Dagger.AnyScope()) + @test MPIExt.mpi_exact_scope_members(mixed) === nothing + @test !MPIExt.mpi_thread_requested(first(cpus), mixed) + cached = MPIExt.mpi_thread_scopes(first(cpus)) + lock(MPIExt.MPI_PROC_CACHE_LOCK) do + MPIExt.invalidate_uniform_cache!(comm) + end + @test MPIExt.mpi_thread_scopes(first(cpus)) !== cached + @test MPIExt.mpi_exact_scope_members(all_threads) !== members +end + +@testset "Serialized MPI scopes retain local identity and hash contracts" begin + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) + original = Dagger.UnionScope(Dagger.ExactScope(first(cpus))) + io = IOBuffer(); Dagger.Serialization.serialize(io, original); seekstart(io) + received = Dagger.Serialization.deserialize(io) + fresh = Dagger.UnionScope(received.scopes) + @test received === fresh + @test hash(received) == hash(fresh) + @test Dict(received => true)[fresh] + # The non-owner receives this scope over MPI's serialized value path. + owner = first(filter(p -> p.rank == 0, cpus)) + portable = fetch(Dagger.@spawn(scope=Dagger.ExactScope(owner), return_type=Dagger.UnionScope, free_scope_value())) + @test portable === Dagger.UnionScope(portable.scopes) + @test portable == free_scope_value() + @test hash(portable) == hash(free_scope_value()) + @test Dict(portable => true)[free_scope_value()] +end + +@testset "Free MPI threads" begin + if Threads.nthreads() >= 2 + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) + rank0 = sort(filter(p -> p.rank == 0, cpus); by=p -> p.innerProc.tid) + # Whole-rank work must run while the other threads remain occupied. + res = free_progress_case(Dagger.scope(mpi_rank=0), rank0, 16) + @test first.(res) == [i + 1 for i in 1:16] + @test all(r -> r[2], res) + @test all(r -> r[3] == first(rank0).innerProc.tid, res) + # Negative control: exact placement on the occupied thread cannot run + # before release, even though another thread is free. + bound = free_progress_case(Dagger.ExactScope(last(rank0)), rank0, 1; + expect_progress=false) + @test only(bound) == (2, false, last(rank0).innerProc.tid) + # An explicit thread is still a promise + where = fetch(Dagger.@spawn scope=Dagger.ExactScope(last(rank0)) free_where()) + @test where == last(rank0).innerProc.tid + end + MPI.Barrier(comm) +end + +# A scope that names some threads of a rank is a request for one of them, not only an +# `ExactScope`: the task must stay on a thread of the scope even while all of them are busy. +@testset "Free MPI threads respect a scope that names threads" begin + if Threads.nthreads() >= 3 + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) + rank0 = sort(filter(p -> p.rank == 0, cpus); by=p -> p.innerProc.tid) + subset = rank0[2:3] + subset_tids = [p.innerProc.tid for p in subset] + subset_scope = Dagger.UnionScope(map(Dagger.ExactScope, subset)) + # Warm up the task shapes first + foreach(fetch, [Dagger.@spawn(scope=subset_scope, free_where()) for _ in 1:4]) + foreach(fetch, [Dagger.@spawn(scope=Dagger.ExactScope(p), hog_busy(0.01)) for p in subset]) + MPI.Barrier(comm) + # Both threads of the scope are busy for a while. A task that did not care would run on + # another thread at once; these must wait for one of the two. + hogs = [Dagger.@spawn(scope=Dagger.ExactScope(p), hog_busy(1.0)) for p in subset] + sleep(0.3) + MPI.Barrier(comm) + tasks = [Dagger.@spawn(scope=subset_scope, free_where()) for _ in 1:6] + tids = fetch.(tasks) + @test all(in(subset_tids), tids) + # The same through `compute_scope`, and with a scope that names every thread of the rank + tasks = [Dagger.@spawn(compute_scope=subset_scope, free_where()) for _ in 1:6] + @test all(in(subset_tids), fetch.(tasks)) + foreach(wait, hogs) + all_threads = Dagger.UnionScope(map(Dagger.ExactScope, rank0)) + res = free_progress_case(all_threads, rank0, 8) + @test first.(res) == [i + 1 for i in 1:8] + @test all(r -> r[2], res) + @test all(r -> r[3] == first(rank0).innerProc.tid, res) + end + MPI.Barrier(comm) +end + +# The task of an MPI processor starts pinned to the thread of its inner processor, so +# `execute!(::ThreadProc)` runs the function inline instead of creating a second pinned task +# and waiting for it (measured: 160-190 us per task). A task that asked for no particular +# thread starts migratable. +@testset "MPI task starts pinned to its processor's thread" begin + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) + mine = first(sort(filter(p -> p.rank == rank, cpus); by=p -> p.innerProc.tid)) + others = filter(p -> p.rank != rank, cpus) + tid_for = Dagger.Sch.task_tid_for_processor + function spec(scope) + task = Dagger.Sch.TaskSpec() + task.scope = scope + task.options = Dagger.Options() + task.Tf = typeof(free_where) + push!(task.data, Dagger.Argument(1, free_where)) + return task + end + # (a rank with one thread has none to choose from: its exact scope leaves nothing out) + nthr = count(p -> p.rank == rank, cpus) + @test tid_for(mine, spec(Dagger.ExactScope(mine))) == (nthr > 1 ? mine.innerProc.tid : nothing) + # A task that did not ask for a thread is not pinned + @test tid_for(mine, spec(nothing)) === nothing + @test tid_for(mine, spec(Dagger.DefaultScope())) === nothing + @test tid_for(mine, spec(Dagger.AnyScope())) === nothing + # A processor of another rank has no thread here + isempty(others) || @test tid_for(first(others), spec(Dagger.ExactScope(first(others)))) === nothing + # And it runs where it was pinned + if rank == 0 + @test fetch(Dagger.@spawn(scope=Dagger.ExactScope(mine), free_where())) == mine.innerProc.tid + else + fetch(Dagger.@spawn(scope=Dagger.ExactScope(first(filter(p -> p.rank == 0, cpus))), free_where())) + end + # A one-member union names a subset on two-thread ranks as well. Exercise + # the union membership cache and pinned pool without requiring three threads. + target = first(sort(filter(p -> p.rank == 0, cpus); by=p -> p.innerProc.tid)) + subset = Dagger.UnionScope(Dagger.ExactScope(target)) + @test MPIExt.mpi_thread_requested(target, subset) == (nthr > 1) + @test tid_for(target, spec(subset)) == (rank == 0 && nthr > 1 ? target.innerProc.tid : nothing) + @test fetch(Dagger.@spawn(scope=subset, free_where())) == target.innerProc.tid + MPI.Barrier(comm) +end + +# In a job of one rank every task is on a communicator of one rank: nobody to tell about its +# status or result type, so none is sent. The result must still be right, and a failure rethrown. +if nranks == 1 + @testset "Task on a one-rank communicator" begin + @test fetch(Dagger.@spawn(free_quick(41))) == 42 + @test fetch(Dagger.@spawn(identity(nothing))) === nothing + t = Dagger.@spawn(error("one-rank failure")) + @test_throws Exception fetch(t) + @test fetch(Dagger.@spawn(free_quick(1))) == 2 # still working afterwards + end +end + +# Explicit allocator tuning keeps freed tile memory in the heap (glibc mallopt); it is a no-op elsewhere +@testset "tune_malloc!" begin + ok = Dagger.tune_malloc!() + @test ok isa Bool + # Idempotent + @test Dagger.tune_malloc!() == ok + # Allocating and freeing a tile-sized libc buffer still works with the settings in place + A = Dagger.alloc_libc_array(Float64, (256, 256)) + A .= 1.0 + @test sum(A) == 256 * 256 +end + +# Compatibility can constrain physical execution even when scope leaves a +# whole rank open. These hooks intentionally support only its last CPU thread. +free_filtered_where() = Threads.threadid() +struct FreeFilteredArgument end +free_filtered_argument(::FreeFilteredArgument) = Threads.threadid() +Dagger.iscompatible_func(p::MPIExt.MPIProcessor{Dagger.ThreadProc}, ::Dagger.Options, + ::Type{typeof(free_filtered_where)}) = + p.innerProc.tid == last(Dagger.default_pool_tids()) +Dagger.iscompatible_arg(p::MPIExt.MPIProcessor{Dagger.ThreadProc}, ::Dagger.Options, + ::Type{FreeFilteredArgument}) = + p.innerProc.tid == last(Dagger.default_pool_tids()) + +@testset "Free MPI execution respects compatibility hooks" begin + cpus = filter(p -> p.rank == 0 && p.innerProc isa Dagger.ThreadProc, mpi_procs()) + target = only(filter(p -> p.innerProc.tid == last(Dagger.default_pool_tids()), cpus)) + scope = Dagger.scope(mpi_rank=0) + spec = Dagger.Sch.TaskSpec() + spec.scope = scope + spec.options = Dagger.Options() + spec.Tf = typeof(free_filtered_where) + push!(spec.data, Dagger.Argument(1, free_filtered_where)) + @test MPIExt.mpi_task_thread_requested(target, spec) == (length(cpus) > 1) + spec.Tf = typeof(free_filtered_argument) + spec.data[1].value = free_filtered_argument + push!(spec.data, Dagger.Argument(2, FreeFilteredArgument())) + @test MPIExt.mpi_task_thread_requested(target, spec) == (length(cpus) > 1) + # A busy eligible thread must still execute these tasks itself; another + # free CPU thread may not bypass the function/argument predicate. + foreach(fetch, Dagger.with_options(; scope) do + [Dagger.@spawn(free_filtered_where()), + Dagger.@spawn(free_filtered_argument(FreeFilteredArgument()))] + end) + warm = Dagger.@spawn scope=Dagger.ExactScope(target) hog_busy(0.01) + wait(warm) + blocker = Dagger.@spawn scope=Dagger.ExactScope(target) hog_busy(1.0) + sleep(0.1) + tasks = Dagger.with_options(; scope) do + [Dagger.@spawn(free_filtered_where()), + Dagger.@spawn(free_filtered_argument(FreeFilteredArgument()))] + end + @test fetch.(tasks) == fill(target.innerProc.tid, 2) + wait(blocker) + MPI.Barrier(comm) +end diff --git a/test/mpi/gpu_suite.jl b/test/mpi/gpu_suite.jl index 3455a28f4..7ed41df4d 100644 --- a/test/mpi/gpu_suite.jl +++ b/test/mpi/gpu_suite.jl @@ -40,6 +40,7 @@ include(joinpath(@__DIR__, "..", "util.jl")) include(joinpath(@__DIR__, "..", "array", "stencil_defs.jl")) include(joinpath(@__DIR__, "..", "array", "sparse_defs.jl")) include(joinpath(@__DIR__, "..", "array", "linalg", "matvec_defs.jl")) +include("elide_gpu.jl") # Broadcast-only mutation helpers (scalar indexing is illegal on GPU arrays) add1!(X) = (X .+= 1; nothing) @@ -91,6 +92,9 @@ function run_mpi_gpu_suite(cfg) cpu_proc_for_rank(r) = first(filter(p->p.rank == r && p.innerProc isa Dagger.ThreadProc, mpi_procs())) gpu_scope(r) = Dagger.ExactScope(gpu_proc_for_rank(r)) cpu_scope(r) = Dagger.ExactScope(cpu_proc_for_rank(r)) + @testset "$(cfg.name) owner elision keeps actual result metadata" begin + test_owner_elision_gpu(gpu_scope(nranks-1)) + end all_gpu_scope() = Dagger.UnionScope([gpu_scope(r) for r in 0:nranks-1]...) # GPU processors are not default-enabled; regions mixing CPU and GPU tasks # must opt in via an outer scope that includes both kinds diff --git a/test/mpi/relay.jl b/test/mpi/relay.jl new file mode 100644 index 000000000..1a41f8b44 --- /dev/null +++ b/test/mpi/relay.jl @@ -0,0 +1,57 @@ +# The broadcast relay must keep forwarding while the driver thread is busy. A relay that shares the +# driver's thread stalls behind a driver parked in a blocking call (a long non-yielding computation, +# an `MPI` collective), and the ranks that wait for what it forwards wait with it. +relay_union_value() = rand() < 2 ? 1 : "never" # non-concrete result type: broadcast to every rank +relay_delayed_union_value(delay::Float64) = (sleep(delay); relay_union_value()) +relay_stamp(x) = time() +relay_hog(seconds::Float64) = (t0 = time(); while time() - t0 < seconds; end; nothing) + +@testset "Broadcast relay is independent of the driver thread" begin + cpus = filter(p -> p.innerProc isa Dagger.ThreadProc, mpi_procs()) + pin(r) = Dagger.ExactScope(last(filter(p -> p.rank == r, cpus))) + # A driver that has scheduled an `@async` task (Distributed's transport does) is thread-bound for + # good, and a `Task` it creates starts on its thread even with `sticky = false`. Restart the relay + # from such a driver, as a session that used Distributed first would have started it. + wait(@async nothing) + @test Base.current_task().sticky + MPI.Barrier(comm) + MPIExt.stop_bcast_relay!(accel.comm) + Dagger.with_options(; scope=pin(0)) do + MPIExt.start_bcast_relay!(accel.comm) + end + relay = lock(MPIExt.BCAST_STATES) do states + states[accel.comm].relay + end + @static if VERSION >= v"1.11-" + @test getfield(relay, :scope) === nothing + else + @test getfield(relay, :logstate) === nothing + end + MPI.Barrier(comm) + # Whatever its placement, it forwards broadcasts + w = Dagger.@spawn scope=pin(0) relay_union_value() + @test fetch(Dagger.@spawn scope=pin(nranks - 1) relay_stamp(w)) isa Float64 + MPI.Barrier(comm) + if nranks >= 2 && Threads.nthreads(:default) >= 4 + # Warm the delayed producer and its consumer before measuring. Its + # metadata must arrive after the destination driver starts its hog, + # rather than slipping through during the planning sleep below. + warm = Dagger.@spawn scope=pin(0) relay_delayed_union_value(0.0) + fetch(Dagger.@spawn scope=pin(nranks - 1) relay_stamp(warm)) + MPI.Barrier(comm) + x = Dagger.@spawn scope=pin(0) relay_delayed_union_value(0.6) + s = Dagger.@spawn scope=pin(nranks - 1) relay_stamp(x) + hog_start = hog_end = 0.0 + if rank == nranks - 1 + sleep(0.2) # let the tasks be planned + hog_start = time() + relay_hog(1.5) + hog_end = time() + end + started = fetch(s) + # All three timestamps come from the destination. The consumer must + # actually start while its driver is unable to forward the metadata. + rank == nranks - 1 && @test hog_start < started < hog_end + MPI.Barrier(comm) + end +end diff --git a/test/mpi/skip_tasks.jl b/test/mpi/skip_tasks.jl new file mode 100644 index 000000000..949f86e7a --- /dev/null +++ b/test/mpi/skip_tasks.jl @@ -0,0 +1,89 @@ +# Dagger.skip_tasks!: a rank that does not take part in a task leaves the @spawn out; ids stay uniform +const SKIP_SEEN = Int[] +const SKIP_LOCK = ReentrantLock() +record_skip(k) = (lock(() -> push!(SKIP_SEEN, k), SKIP_LOCK); k) +@testset "skip_tasks!: ids stay uniform when ranks skip foreign tasks" begin + nr = MPI.Comm_size(comm); me = MPI.Comm_rank(comm) + own_task(x) = x + 1 + old = Dagger.ELIDE_FOREIGN_TASKS[] + # Uniformity checks are collective over all ranks and so disable elision (and with it skipping) + Dagger.check_uniformity!(false) + Dagger.elide_foreign_tasks!(true) + try + before = Dagger.ID_COUNTER[] + eager_before = Dagger.Sch.EAGER_STATE[] + Dagger.check_uniformity!(true) + @test_throws ArgumentError Dagger.skip_tasks!(1) + @test Dagger.ID_COUNTER[] == before + @test Dagger.Sch.EAGER_STATE[] === eager_before + Dagger.check_uniformity!(false) + @test_throws ArgumentError Dagger.skip_tasks!(big(typemax(Int)) + 1) + @test Dagger.ID_COUNTER[] == before + @test Dagger.Sch.EAGER_STATE[] === eager_before + # No warm-up: the first thing a rank does may be to skip (starting the eager scheduler draws an id, see skip_tasks!) + # ASYMMETRIC on purpose: rank 0 takes part in all N tasks, the others in none (a symmetric batch hides counter drift). + # No fetch of a skipped task: a fetch is a collective (the owner sends the value to every rank) and draws ids. + N = 7 + empty!(SKIP_SEEN) + ts = Any[] + for k in 1:N + if me == 0 + push!(ts, Dagger.@spawn scope=Dagger.scope(mpi_rank=0) return_type=Int record_skip(k)) + else + Dagger.skip_tasks!(1) + end + end + if me == 0 + t0 = time(); while length(SKIP_SEEN) < N && time() - t0 < 30; sleep(0.01); end # a failure-only task is not waited for by `wait` + @test sort(SKIP_SEEN) == collect(1:N) + end + # the next task of the shared counter has the same id on every rank, past the batch + nxt = Dagger.@spawn scope=Dagger.scope(mpi_rank=0) return_type=Int own_task(0) + uids = MPI.Allgather([Int(nxt.uid)], comm) + @test allequal(uids) + @test fetch(nxt) == 1 + if me == 0 + # consecutive: nothing else drew from the counter (the first task of the process is followed by the id the eager scheduler takes) + mine = [Int(t.uid) for t in ts] + @test mine[2:end] == collect(mine[2]:mine[2] + N - 2) + end + @testset "integer inputs and rejected calls preserve the counter" begin + for n in (Int8(1), UInt(1), BigInt(1)) + before = Dagger.ID_COUNTER[] + Dagger.skip_tasks!(n) + @test Dagger.ID_COUNTER[] == before + 1 + end + before = Dagger.ID_COUNTER[] + @test_throws ArgumentError Dagger.skip_tasks!(big(typemax(Int)) + 1) + @test Dagger.ID_COUNTER[] == before + accel = Dagger.current_acceleration() + rejected = Threads.@spawn try + Dagger.skip_tasks!(accel, 1) + false + catch err + err isa ConcurrencyViolationError + end + @test fetch(rejected) + @test Dagger.ID_COUNTER[] == before + end + @testset "skipped failures have no retained consumer" begin + ext = Base.get_extension(Dagger, :MPIExt) + tid = UInt32(Dagger.ID_COUNTER[]) + # Delivery may arrive before the rank skips, or after it. Neither + # notification has a handle which could later consume its error. + ext.owner_elision_deliver!(0, tid, ErrorException("early skipped failure")) + @test (@lock ext.OWNER_ELISION_LOCK haskey(ext.OWNER_ELISION_EARLY, tid)) + Dagger.skip_tasks!(1) + @test (@lock ext.OWNER_ELISION_LOCK !haskey(ext.OWNER_ELISION_EARLY, tid)) + ext.owner_elision_deliver!(0, tid, ErrorException("late skipped failure")) + @test (@lock ext.OWNER_ELISION_LOCK !haskey(ext.OWNER_ELISION_EARLY, tid)) + end + # several at once, none, and a negative count + Dagger.skip_tasks!(0) + @test_throws ArgumentError Dagger.skip_tasks!(-1) + finally + Dagger.elide_foreign_tasks!(old) + Dagger.check_uniformity!(true) + end + @test_throws ArgumentError (Dagger.elide_foreign_tasks!(false); try Dagger.skip_tasks!(1) finally Dagger.elide_foreign_tasks!(old) end) +end diff --git a/test/mpi/spawn.jl b/test/mpi/spawn.jl index 5a87f385f..83c3d37ec 100644 --- a/test/mpi/spawn.jl +++ b/test/mpi/spawn.jl @@ -1,18 +1,23 @@ # Plain eager tasks need a uniform placement decision even when ranks make # progress at different speeds. Check actual execution, scopes, and locality. +# A task whose scope excludes some thread of its rank asked for a thread, and must run on the +# processor's thread. Any other task runs on whichever thread of its rank is free (see +# `free_threads.jl`), so only its rank is the planner's choice. mpi_spawn_location(x=nothing) = (MPI.Comm_rank(MPI.COMM_WORLD), Threads.threadid(), x) mpi_spawn_value() = (sleep(0.05); 42) mpi_spawn_value_fast(i) = 42 + i - i mpi_spawn_checked(i::Int) = i > 0 ? i : error("negative") -function check_spawn_placements(tasks, allowed, value=nothing) +function check_spawn_placements(tasks, allowed, value=nothing; pinned=false) placements = Dagger.Processor[] for task in tasks proc = fetch(task; raw=true).processor push!(placements, proc) @test proc in allowed @test Dagger.check_uniform(proc) - @test fetch(task) == (proc.rank, proc.innerProc.tid, value) + loc = fetch(task) + @test loc[1] == proc.rank && loc[3] == value + pinned && @test loc[2] == proc.innerProc.tid end @test [count(==(p), placements) for p in allowed] == fill(4, length(allowed)) end @@ -50,7 +55,7 @@ end end foreach(wait, tasks) Dagger.check_uniformity!(true) - check_spawn_placements(tasks, allowed) + check_spawn_placements(tasks, allowed; pinned=label in ("compute scope", "exact scope")) end @testset "Chunk owner preference" begin diff --git a/test/options.jl b/test/options.jl index 72d911275..370f786f8 100644 --- a/test/options.jl +++ b/test/options.jl @@ -19,7 +19,7 @@ end end Dagger.move(from::Union{OSProc,Dagger.ThreadProc}, to::Dagger.ThreadProc, sf::SpecialFunc) = - (to.owner == 1 && to.tid == 1) ? SpecialFunc(1) : sf + (to.owner == 1 && to.tid == Dagger.first_default_tid()) ? SpecialFunc(1) : sf end option_default_target(x; ignored=nothing) = x @@ -140,12 +140,12 @@ end sf = SpecialFunc(0) obj = Dagger.tochunk(42) if nprocs() > 1 - Dagger.with_options(;scope=Dagger.ExactScope(Dagger.ThreadProc(first_wid,1))) do + Dagger.with_options(;scope=Dagger.ExactScope(Dagger.first_thread_proc(first_wid))) do @test fetch(Dagger.@spawn sf(obj)) == 0 @test fetch(Dagger.@spawn sf(obj)) == 0 end end - Dagger.with_options(;scope=Dagger.ExactScope(Dagger.ThreadProc(1,1)), meta=true) do + Dagger.with_options(;scope=Dagger.ExactScope(Dagger.first_thread_proc(1)), meta=true) do @test fetch(Dagger.@spawn sf(obj)) == 43 @test fetch(Dagger.@spawn sf(obj)) == 43 end @@ -156,7 +156,7 @@ end # filter, or reorder them, however many tasks are spawned. scoped_props = Symbol[:scope] Dagger.with_options(; propagates=scoped_props, - scope=Dagger.ExactScope(Dagger.ThreadProc(1,1))) do + scope=Dagger.ExactScope(Dagger.first_thread_proc(1))) do @test fetch(Dagger.@spawn 1+1) == 2 @test fetch(Dagger.@spawn 1+1) == 2 end diff --git a/test/processors.jl b/test/processors.jl index 3d0564be6..d2ecbaa23 100644 --- a/test/processors.jl +++ b/test/processors.jl @@ -110,4 +110,73 @@ end end @test Dagger.num_processors(;all=true) == length(all_procs) end + + @testset "ThreadProcs are the default thread pool" begin + # Holds however this process was started, including with an + # interactive thread (Julia 1.12's default). + thread_tids(pid) = sort!([p.tid for p in get_processors(OSProc(pid)) if p isa ThreadProc]) + @test thread_tids(myid()) == Threads.threadpooltids(:default) + @test Dagger.first_default_tid() == first(Threads.threadpooltids(:default)) + + # Make sure an interactive thread exists, whatever the Julia version or + # the flags this suite was started with. It takes thread 1, so the + # default pool is threads 2 and 3. + script = """ + using Dagger, Test + const Distributed = parentmodule(Dagger.myid) + using .Distributed + worker = only(addprocs(1; exeflags=`--project=\$(Base.active_project()) -t 2,2`)) + @everywhere using Dagger + default_tids = Threads.threadpooltids(:default) + interactive_tids = Threads.threadpooltids(:interactive) + threadprocs = sort!([p for p in Dagger.get_processors(Dagger.OSProc()) + if p isa Dagger.ThreadProc]; by=p->p.tid) + proc_tids = [p.tid for p in threadprocs] + # Where a task pinned to each ThreadProc actually runs + exact_tids = [fetch(Dagger.@spawn scope=Dagger.ExactScope(p) Threads.threadid()) + for p in threadprocs] + # Where tasks scoped to this worker run without an exact thread + sleep_tid() = (sleep(0.05); Threads.threadid()) + free_tids = sort!(unique(fetch.( + [Dagger.@spawn scope=Dagger.scope(worker=myid()) sleep_tid() for _ in 1:16]))) + # Worker-ID assignment picks the worker's first CPU thread + A = Dagger.distribute(ones(4, 4), Dagger.Blocks(2, 2), fill(1, 2, 2)) + grid_tids = sort!(unique([fetch(c; raw=true).processor.tid for c in A.chunks])) + worker_first_tid = first(remotecall_fetch(Threads.threadpooltids, worker, :default)) + data = reshape(collect(1:16), 4, 4) + B = Dagger.distribute(data, Dagger.Blocks(2, 2), fill(worker, 2, 2)) + mixed_grid = unique([fetch(c; raw=true).processor for c in B.chunks]) + mixed_grid_ok = mixed_grid == [Dagger.ThreadProc(worker, worker_first_tid)] && + collect(B) == data + rmprocs(worker) + @testset "Interactive-thread subprocess" begin + @test interactive_tids == [1] + @test default_tids == [2, 3] + @test proc_tids == default_tids + @test exact_tids == default_tids + @test isempty(intersect(free_tids, interactive_tids)) + @test free_tids ⊆ default_tids + @test grid_tids == [first(default_tids)] + @test worker_first_tid == 3 + @test mixed_grid_ok + end + """ + # Resolve packages and preferences (the transport) like this process + load_path = join(Base.load_path(), Sys.iswindows() ? ';' : ':') + cmd = addenv(`$(Base.julia_cmd()) --startup-file=no -t 2,1 -e $script`, + "JULIA_LOAD_PATH" => load_path) + out = IOBuffer() + child = run(pipeline(cmd; stdout=out, stderr=out); wait=false) + deadline = time() + 600 + while process_running(child) && time() < deadline + sleep(0.5) + end + process_running(child) && kill(child, Base.SIGKILL) + wait(child) + output = String(take!(out)) + @test success(child) + if !success(child) + println(stderr, "Interactive-thread subprocess output:\n", output) + end + end end diff --git a/test/reuse-task-cache.jl b/test/reuse-task-cache.jl index 2ffe70e8e..aeac6372a 100644 --- a/test/reuse-task-cache.jl +++ b/test/reuse-task-cache.jl @@ -58,3 +58,49 @@ using Test finalize(empty_cache) @test all(i -> !isassigned(empty_cache.chans, i), 1:empty_cache.N) end + +@testset "Migratable task slots recover after async payloads" begin + cache = Dagger.ReusableTaskCache(1) + Dagger.reusable_task_cache_init!(Dagger.set_task_migratable!, cache) + entered = Channel{Task}(1) + release = Base.Event() + child_done = Base.Event() + poisoned = cache(() -> begin + @async begin + put!(entered, current_task()) + wait(release) + notify(child_done) + end + end, "async payload") + child = take!(entered) + @test timedwait(() -> cache.ready[1][], 10.0; pollint=0.001) === :ok + @test poisoned.sticky + @test !isopen(cache.chans[1]) + @test !istaskdone(child) + tasks = Channel{Tuple{Task,Bool}}(1) + fresh = cache(() -> put!(tasks, (current_task(), current_task().sticky)), "fresh async slot") + @test take!(tasks) === (fresh, false) + @test fresh !== poisoned + @test timedwait(() -> cache.ready[1][], 10.0; pollint=0.001) === :ok + # A clean payload still reuses the replacement slot. + @test cache(() -> put!(tasks, (current_task(), current_task().sticky)), "reused fresh slot") === fresh + @test take!(tasks) === (fresh, false) + notify(release) + wait(child_done) + @test timedwait(() -> cache.ready[1][], 10.0; pollint=0.001) === :ok + finalize(cache) + wait(fresh) + @test !istaskfailed(poisoned) + + # Intentionally pinned slots keep their identity across async payloads. + pinned = Dagger.ReusableTaskCache(1) + Dagger.reusable_task_cache_init!(t -> nothing, pinned) + done = Base.Event() + first = pinned(() -> wait(@async nothing), "pinned async slot") + @test timedwait(() -> pinned.ready[1][], 10.0; pollint=0.001) === :ok + @test pinned(() -> notify(done), "pinned reused slot") === first + wait(done) + @test timedwait(() -> pinned.ready[1][], 10.0; pollint=0.001) === :ok + finalize(pinned) + wait(first) +end diff --git a/test/scheduler.jl b/test/scheduler.jl index 4d7637f77..d7c663980 100644 --- a/test/scheduler.jl +++ b/test/scheduler.jl @@ -391,8 +391,8 @@ end end state = Dagger.Sch.EAGER_STATE[] - tproc1_1 = Dagger.ThreadProc(1, 1) - tproc2_1 = Dagger.ThreadProc(first(workers()), 1) + tproc1_1 = Dagger.first_thread_proc(1) + tproc2_1 = Dagger.first_thread_proc(first(workers())) procs = [tproc1_1, tproc2_1] # Ensure that this worker has been used at least once @@ -779,7 +779,7 @@ end @testset "Cancellation" begin # Ready task cancellation start_time = time_ns() - t = Dagger.@spawn scope=Dagger.scope(worker=1, thread=1) sleep(100) + t = Dagger.@spawn scope=Dagger.scope(worker=1, thread=Dagger.first_default_tid()) sleep(100) Dagger.cancel!(t) @test timedwait(()->istaskdone(t), 10) == :ok if istaskdone(t) @@ -789,7 +789,7 @@ end # Running task cancellation start_time = time_ns() - t = Dagger.@spawn scope=Dagger.scope(worker=1, thread=1) sleep(100) + t = Dagger.@spawn scope=Dagger.scope(worker=1, thread=Dagger.first_default_tid()) sleep(100) sleep(0.1) # Give the scheduler a chance to schedule the task Dagger.cancel!(t) @test timedwait(()->istaskdone(t), 10) == :ok @@ -800,7 +800,7 @@ end # Normal task execution start_time = time_ns() - t = Dagger.@spawn scope=Dagger.scope(worker=1, thread=1) yield() + t = Dagger.@spawn scope=Dagger.scope(worker=1, thread=Dagger.first_default_tid()) yield() @test timedwait(()->istaskdone(t), 10) == :ok if istaskdone(t) @test (time_ns() - start_time) * 1e-9 < 100 diff --git a/test/scopes.jl b/test/scopes.jl index c448bf2ca..6f63bb9b0 100644 --- a/test/scopes.jl +++ b/test/scopes.jl @@ -27,7 +27,10 @@ ps1_ch = Dagger.tochunk(nothing, OSProc(), ps1) ps2_ch = Dagger.tochunk(nothing, OSProc(), ps2) - es1, es2 = ExactScope(Dagger.ThreadProc(wid1, 1)), ExactScope(Dagger.ThreadProc(wid2, 2)) + # The workers' first two threads: not 1 and 2 when they have an + # interactive thread (Julia 1.12+ adds one to `-t2`) + t1, t2 = remotecall_fetch(Dagger.default_pool_tids, wid1) + es1, es2 = ExactScope(Dagger.ThreadProc(wid1, t1)), ExactScope(Dagger.ThreadProc(wid2, t2)) es1_ch = Dagger.tochunk(nothing, OSProc(), es1) es2_ch = Dagger.tochunk(nothing, OSProc(), es2) @@ -96,11 +99,11 @@ # One process ts = fetch.([Dagger.@spawn exact_scope_test(isodd(i) ? es1_ch : es2_ch) for i in 1:20]) @test all(x->x.owner==wid1, ts[1:2:20]) - @test all(x->x.owner==wid2&&x.tid==2, ts[2:2:20]) + @test all(x->x.owner==wid2&&x.tid==t2, ts[2:2:20]) # Same process t = fetch(Dagger.@spawn exact_scope_test(es1_ch, es1_ch)) - @test t.owner == wid1 && t.tid == 1 + @test t.owner == wid1 && t.tid == t1 # Different process, different processor for (ch1, ch2) in [(es1_ch, es2_ch), (es2_ch, es1_ch)] @@ -108,7 +111,7 @@ end # Same process, different processor - es1_2 = ExactScope(Dagger.ThreadProc(wid1, 2)) + es1_2 = ExactScope(Dagger.ThreadProc(wid1, t2)) es1_2_ch = Dagger.tochunk(nothing, OSProc(), es1_2) for (ch1, ch2) in [(es1_ch, es1_2_ch), (es1_2_ch, es1_ch)] @test_throws_unwrap (Dagger.DTaskFailedException, Dagger.Sch.SchedulingException) reason<"Current scope and argument Chunk scope are not compatible:" fetch(Dagger.@spawn ch1 + ch2) @@ -255,13 +258,13 @@ @test all(proc->proc in comp_procs, Dagger.get_processors(OSProc(wid1))) @test !any(proc->proc in comp_procs, Dagger.get_processors(OSProc(wid2))) - scope = Dagger.scope(worker=wid1, thread=2) + scope = Dagger.scope(worker=wid1, thread=t2) comp_procs = Dagger.compatible_processors(scope) @test Dagger.num_processors(scope) == length(comp_procs) @test length(comp_procs) == 1 @test !all(proc->proc in comp_procs, Dagger.get_processors(OSProc(wid1))) @test !all(proc->proc in comp_procs, Dagger.get_processors(OSProc(wid2))) - @test Dagger.ThreadProc(wid1, 2) in comp_procs + @test Dagger.ThreadProc(wid1, t2) in comp_procs scope = Dagger.scope(workers=[wid1, wid2]) comp_procs = Dagger.compatible_processors(scope) @@ -275,7 +278,7 @@ @testset "scope comparison" begin scope1 = Dagger.scope(worker=wid1) - scope2 = Dagger.scope(worker=wid1, thread=1) + scope2 = Dagger.scope(worker=wid1, thread=t1) @test issubset(scope2, scope1) @test !issubset(scope1, scope2) @test issetequal(scope1, scope1) @@ -286,3 +289,40 @@ rmprocs([wid1, wid2]) end + +@testset "UnionScope constrained by AnyScope is itself" begin + u = Dagger.UnionScope([Dagger.ExactScope(Dagger.ThreadProc(1, t)) for t in 1:8]) + # `schedule_one!` does this for every task without a result scope; it must neither rebuild the union nor change it + @test Dagger.constrain(u, Dagger.AnyScope()) === u + @test Dagger.constrain(Dagger.AnyScope(), u) === u + @test Dagger.constrain(u, Dagger.AnyScope(), Dagger.AnyScope()) === u + # and a union is still narrowed by something that is not AnyScope + narrowed = Dagger.constrain(u, Dagger.ExactScope(Dagger.ThreadProc(1, 3))) + @test narrowed isa Dagger.UnionScope && length(narrowed.scopes) == 1 +end + +@testset "Equal taint scopes have equal hashes" begin + for original in (Dagger.DefaultScope(), Dagger.ProcessorTypeScope(Dagger.ThreadProc)) + io = IOBuffer(); Dagger.Serialization.serialize(io, original); seekstart(io) + received = Dagger.Serialization.deserialize(io) + @test original == received + @test hash(original) == hash(received) + @test Dict(original => true)[received] + end +end + +@testset "Scope serialization rebuilds derived membership metadata" begin + for original in (UnionScope(ExactScope(Dagger.ThreadProc(1, 1))), + UnionScope(Dagger.ProcessorTypeScope(Dagger.ThreadProc))) + io = IOBuffer() + Dagger.Serialization.serialize(io, original) + seekstart(io) + received = Dagger.Serialization.deserialize(io) + fresh = UnionScope(received.scopes) + @test received === fresh + @test hash(received) == hash(fresh) + @test Dict(received => true)[fresh] + @test original == received + @test hash(original) == hash(received) + end +end diff --git a/test/streaming.jl b/test/streaming.jl index 6e0b57f66..afcb8549c 100644 --- a/test/streaming.jl +++ b/test/streaming.jl @@ -412,12 +412,13 @@ Base.take!(b::ParkSignalBuffer) = take!(b.inner) end all_scopes = [Dagger.ExactScope(proc) for proc in Dagger.all_processors()] +# Each worker's first thread is not thread 1 when it has an interactive thread for idx in 1:5 if idx == 1 - scopes = [Dagger.scope(worker = 1, thread = 1)] + scopes = [Dagger.ExactScope(Dagger.first_thread_proc(1))] scope_str = "Worker 1" elseif idx == 2 && nprocs() > 1 - scopes = [Dagger.scope(worker = 2, thread = 1)] + scopes = [Dagger.ExactScope(Dagger.first_thread_proc(2))] scope_str = "Worker 2" else scopes = all_scopes diff --git a/test/task-affinity.jl b/test/task-affinity.jl index 58a7b5c21..f773859f8 100644 --- a/test/task-affinity.jl +++ b/test/task-affinity.jl @@ -40,7 +40,7 @@ availscopes = shuffle!(Dagger.ExactScope.(availprocs)) numscopes = length(availscopes) - master_proc = Dagger.ThreadProc(1, 1) + master_proc = Dagger.first_thread_proc(1) master_scope = Dagger.ExactScope(master_proc) @testset "scope, compute_scope and result_scope" begin diff --git a/test/thunk.jl b/test/thunk.jl index 900ba354c..14b1607be 100644 --- a/test/thunk.jl +++ b/test/thunk.jl @@ -507,7 +507,8 @@ end @testset "parent fetch child, one thread" begin # Issue #282 - s = p -> p == Dagger.ThreadProc(1, 1) + thread1 = Dagger.first_thread_proc(1) + s = p -> p == thread1 f = (x) -> 10 + x g = (x) -> fetch(Dagger.@spawn proclist=s f(x)) fetch(Dagger.@spawn proclist=s g(10))