Skip to content
Merged
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
8 changes: 7 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -1218,7 +1218,13 @@ this section verbatim). Each entry is one bullet starting with `- `.
*and* a remote writer, in both orders: in one process every slot is the
argument itself, so none of this is visible.

109. **Report upstream failures without surviving workflow cancellation.** A
109. **Disabling interactive threads needs version-specific Julia CLI flags.**
Julia 1.10 and 1.11 reject `-t N,0`; their `-t N` already creates only
default-pool threads. On Julia 1.12 and later, `-t N` adds an interactive
thread, so use `-t N,0` when a subprocess requires no interactive pool.
Test the old parser as well as modern pool placement.

110. **Report upstream failures without surviving workflow cancellation.** A
job guarded by `always()` remains eligible after cancellation. Superseded
PR runs were left queued on the combined benchmark summary and held their
per-ref concurrency slots; normal cancellation left that summary queued.
Expand Down
1 change: 1 addition & 0 deletions docs/make.jl
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ makedocs(;
],
"Task Spawning" => "task-spawning.md",
"Task Affinity" => "task-affinity.md",
"Thread Pinning" => "threadpinning.md",
"Data Management" => "data-management.md",
"Distributed Arrays" => "darray.md",
"Sparse Arrays" => "sparse-arrays.md",
Expand Down
101 changes: 101 additions & 0 deletions docs/src/threadpinning.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# Thread Pinning

Dagger runs a task on a Julia thread, and the operating system is free to move
that thread between CPUs. On machines where placement matters (several NUMA
domains, several jobs sharing one node, memory-bound kernels) it helps to pin
Julia's threads to CPUs. Dagger does not provide its own pinning API for this.
Use [ThreadPinning.jl](https://github.com/carstenbauer/ThreadPinning.jl), which
works on the Julia threads that Dagger's `ThreadProc`s run on, and needs no
cooperation from Dagger.

!!! note
Pinning only works in practice on Linux. On other systems ThreadPinning
either does nothing or is not supported, and the test that accompanies this
page is skipped there.

## Basic usage

Install ThreadPinning 1.x (`using Pkg; Pkg.add(name="ThreadPinning", version="1")`),
then pin once, before submitting work:

```julia
using Dagger, ThreadPinning

pinthreads(:affinitymask)
```

`:affinitymask` pins each thread of the default thread pool to one CPU, staying
inside the CPU mask the process was started with. That mask can come from the
job launcher, from `taskset`, or from `numactl`. For example, with

```sh
taskset -c 4-7 julia -t 4
```

the four threads end up on four distinct CPUs of 4-7, and every Dagger task then
runs on exactly one of those CPUs. Calling `pinthreads(:affinitymask)` a second
time gives the same result. `ThreadPinning.getcpuids()` shows where the threads
are, and `ThreadPinning.getcpuid()` called inside a task shows where that task
runs:

```julia
Dagger.@spawn scope=Dagger.scope(worker=1, thread=2) ThreadPinning.getcpuid()
```

## Pitfalls

1. **Use ThreadPinning 1.x.** An unconstrained `Pkg.add("ThreadPinning")` can
resolve to 0.7.x, which has no `:affinitymask`. Ask for `version="1"`
(or `ThreadPinning = "1"` in `[compat]`).

2. **Call `addprocs` before pinning.** If the main thread is in the default
thread pool, `pinthreads` pins it to one CPU, and processes started
afterwards inherit that single CPU. (On Julia 1.12 and later, with an
interactive thread, the main thread stays unpinned.)

3. **Workers on the same node need separate CPUs.** Each worker pins inside
the mask it inherited, so by default all workers of one node would pin onto
the same CPUs. Split the mask explicitly:

```julia
using Distributed
addprocs(2; exeflags=`--threads=2`) # before pinning
@everywhere using Dagger, ThreadPinning

cpus = findall(isone, getaffinity()) .- 1 # CPUs of this process's mask
for (k, w) in enumerate(workers())
nt = remotecall_fetch(() -> Threads.nthreads(:default), w)
remotecall_wait(pinthreads, w, cpus[(k-1)*nt+1:k*nt])
end
```

`distributed_pinthreads(:cores)` splits over the whole machine and ignores
the mask, so it is not a substitute when the processes run under `taskset`
or inside a job allocation.

MPI ranks do not need any of this when the launcher binds them to CPUs
(for example `mpiexec --bind-to core`, or `srun --cpu-bind`): each rank then
calls `pinthreads(:affinitymask)` and pins inside its own binding.

4. **Interactive threads.** With an interactive thread (`julia -t 4,1`),
Dagger currently registers `ThreadProc`s for thread ids `1:Threads.nthreads()`.
That includes the interactive thread 1, which `pinthreads(:affinitymask)`
leaves unpinned, and leaves out the last default thread. This is being fixed
in [#841](https://github.com/JuliaParallel/Dagger.jl/pull/841). Until then
either start Julia without interactive threads (`-t N` on Julia 1.10/1.11,
`-t N,0` on Julia 1.12 and later), or pin all threads:

```julia
pinthreads(:affinitymask; threadpool=:all,
nthreads=Threads.nthreads(:default) + Threads.nthreads(:interactive))
```

## What was tested

`test/threadpinning.jl` starts Julia subprocesses under `taskset -c <CPUs>` with
a range that does not start at CPU 0, runs Dagger tasks, calls
`pinthreads(:affinitymask)` twice, and checks that every default thread, and the
CPU reported from inside a Dagger task on each thread, lies inside the mask, that
the threads are on distinct CPUs, and that the second call changes nothing. It is
skipped when the system is not Linux, when `taskset` is missing, when fewer than
four CPUs are allowed, or when ThreadPinning cannot be loaded.
2 changes: 2 additions & 0 deletions test/Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,12 @@ Serialization = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
ThreadPinning = "811555cd-349b-4f26-b7bc-1f208b848042"
TimespanLogging = "a526e669-04d3-4846-9525-c66122c55f63"
UUIDs = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"

[compat]
ThreadPinning = "1"
# Drop once SparseColumnPivotedQR ≥ 2.1.8 is registered (SciML/SparseColumnPivotedQR.jl#71).
AMD = "0.5.1 - 0.5.3"

Expand Down
1 change: 1 addition & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ tests = [
("Mutation", "mutation.jl"),
("Task Queues", "task-queues.jl"),
("Task Affinity", "task-affinity.jl"),
("Thread Pinning", "threadpinning.jl"),
("Datadeps", "datadeps.jl"),
("Streaming", "streaming.jl"),
("Domain Utilities", "domain.jl"),
Expand Down
104 changes: 104 additions & 0 deletions test/threadpinning.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# Checks that ThreadPinning.jl pins the threads Dagger runs tasks on, inside the
# CPU mask a process was started with (see docs/src/threadpinning.md).
# Linux only: skipped without Linux, `taskset`, four allowed CPUs, or ThreadPinning.

# CPU ids listed in the process's affinity mask (Linux: /proc/self/status).
function allowed_cpu_ids()
cpus = Int[]
for line in eachline("/proc/self/status")
m = match(r"^Cpus_allowed_list:\s*(\S+)", line)
m === nothing && continue
for part in split(m.captures[1], ',')
r = split(part, '-')
append!(cpus, length(r) == 1 ? [parse(Int, r[1])] :
collect(parse(Int, r[1]):parse(Int, r[2])))
end
end
return sort!(cpus)
end

const PINNING_CHILD_SCRIPT = raw"""
using Dagger, ThreadPinning
nt = Threads.nthreads(:default)
# Run some tasks first, so pinning happens on a warmed-up scheduler.
fetch.([Dagger.@spawn(sum(1:100)) for _ in 1:8])
pinthreads(:affinitymask)
first_ids = collect(getcpuids())
pinthreads(:affinitymask)
second_ids = collect(getcpuids())
println("FIRST ", join(first_ids, ","))
println("SECOND ", join(second_ids, ","))
# Ask each thread's processor where its tasks run.
where_am_i() = (Threads.threadid(), ThreadPinning.getcpuid())
for t in 1:nt
t_ = Dagger.@spawn scope=Dagger.scope(worker=1, thread=t) where_am_i()
tid, cpu = fetch(t_)
println("TASK ", t, " ", tid, " ", cpu)
end
"""

function run_pinned_child(cpu_list::String, nthreads::Int)
mktempdir() do dir
script = joinpath(dir, "child.jl")
write(script, PINNING_CHILD_SCRIPT)
load_path = join(Base.load_path(), ':')
# Julia 1.10/1.11 reject an explicit zero interactive count. Their
# single-count form already starts without interactive threads.
thread_spec = VERSION < v"1.12" ? string(nthreads) : "$nthreads,0"
cmd = `taskset -c $cpu_list $(Base.julia_cmd()) --startup-file=no -t $thread_spec $script`
cmd = addenv(cmd, "JULIA_LOAD_PATH" => load_path)
out = IOBuffer()
proc = run(pipeline(ignorestatus(cmd); stdout=out, stderr=stderr))
return proc.exitcode, String(take!(out))
end
end

@testset "ThreadPinning" begin
skip_reason = if !Sys.islinux()
"pinning is only exercised on Linux"
elseif Sys.which("taskset") === nothing
"`taskset` not found"
elseif Base.find_package("ThreadPinning") === nothing
"ThreadPinning is not available"
elseif length(allowed_cpu_ids()) < 4
"fewer than four CPUs allowed"
else
nothing
end

if skip_reason !== nothing
@info "Skipping ThreadPinning test: $skip_reason"
@test_skip false
else
allowed = allowed_cpu_ids()
for nthreads in (2, 4)
# The last `nthreads` allowed CPUs: a mask that does not start at
# CPU 0 whenever more CPUs than threads are allowed.
mask = allowed[end-nthreads+1:end]
code, out = run_pinned_child(join(mask, ','), nthreads)
@test code == 0
first_ids = second_ids = Int[]
task_cpus = Int[]
task_tids = Int[]
for line in split(out, '\n')
f = split(strip(line))
isempty(f) && continue
if f[1] == "FIRST"
first_ids = parse.(Int, split(f[2], ','))
elseif f[1] == "SECOND"
second_ids = parse.(Int, split(f[2], ','))
elseif f[1] == "TASK"
push!(task_tids, parse(Int, f[3])); push!(task_cpus, parse(Int, f[4]))
end
end
@test length(first_ids) == nthreads
# getcpuids is 0-based, like the mask above
@test all(in(mask), first_ids)
@test allunique(first_ids)
@test second_ids == first_ids
@test task_tids == collect(1:nthreads)
@test all(in(mask), task_cpus)
@test allunique(task_cpus)
end
end
end
Loading