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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -1217,3 +1217,54 @@ 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. **Work stealing must repeat function and argument compatibility checks.**
A processor being inside a task's scope says nothing about whether it can
execute that function. CPU runners used to steal Python tasks from their
correctly selected PythonProcessor queue, bypassing PythonExt's CPU
exclusion and invoking CPython without its GIL. Excluding interactive
threads made this much more likely by removing the protected main-thread
runner. Check function and argument types before removing a queued task,
and enter the latest world for those hooks: a runner may predate the
extension. Test a restricted callable and a restricted argument separately;
a scope-only test cannot detect this violation.

113. **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.
27 changes: 18 additions & 9 deletions docs/src/darray.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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):

Expand Down Expand Up @@ -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}:
Expand All @@ -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)
```

Expand Down
48 changes: 34 additions & 14 deletions docs/src/task-affinity.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.

---

Expand All @@ -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.

---

Expand All @@ -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.

---

Expand All @@ -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`.

Expand All @@ -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.

Expand All @@ -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.
4 changes: 3 additions & 1 deletion ext/MPIExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2504,7 +2504,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
Expand Down
59 changes: 57 additions & 2 deletions ext/PythonExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -38,17 +43,67 @@ 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...)
# Match this branch's inline CPU wrapper without changing its generic path.
if Dagger.task_logging_enabled()
Dagger.TimespanLogging.prof_task_put!(Dagger.get_tls().sch_handle.thunk_id.id)
end
try
return Base.invokelatest(Dagger.execute!, PythonProcessor(proc.owner),
f, args...; kwargs...)
catch err
err isa InterruptException && rethrow()
rethrow(CapturedException(err, catch_backtrace()))
end
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
Expand Down
6 changes: 5 additions & 1 deletion src/Dagger.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading