From d65e3794dc28da8ff36bf8adfb78492075dbb313 Mon Sep 17 00:00:00 2001 From: Anna-Lena Date: Sun, 29 Nov 2026 11:32:15 +0100 Subject: [PATCH 1/2] Docs and test: use ThreadPinning.jl to pin Dagger's threads Add a usage guide for pinning Julia's threads with ThreadPinning.jl instead of a Dagger-specific API: basic use with pinthreads(:affinitymask), and the pitfalls (ThreadPinning 1.x, addprocs before pinning, separate CPUs for same-node workers, interactive threads). Add a Linux-only test that starts Julia under taskset -c with a CPU range, pins, and checks that the threads, and the CPUs seen from inside Dagger tasks, lie inside the mask, are distinct, and are unchanged by a second call. It is skipped without Linux, taskset, four allowed CPUs, or ThreadPinning. ThreadPinning is a test-only dependency. --- docs/make.jl | 1 + docs/src/threadpinning.md | 100 +++++++++++++++++++++++++++++++++++++ test/Project.toml | 2 + test/runtests.jl | 1 + test/threadpinning.jl | 101 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 205 insertions(+) create mode 100644 docs/src/threadpinning.md create mode 100644 test/threadpinning.jl diff --git a/docs/make.jl b/docs/make.jl index d7f6f0168..9568c9772 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -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", diff --git a/docs/src/threadpinning.md b/docs/src/threadpinning.md new file mode 100644 index 000000000..3baa8ddd5 --- /dev/null +++ b/docs/src/threadpinning.md @@ -0,0 +1,100 @@ +# 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,0`), 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 ` 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. diff --git a/test/Project.toml b/test/Project.toml index da151f31b..6446b58a9 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -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" diff --git a/test/runtests.jl b/test/runtests.jl index 35aa76788..edcdd1da1 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -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"), diff --git a/test/threadpinning.jl b/test/threadpinning.jl new file mode 100644 index 000000000..99af08eb4 --- /dev/null +++ b/test/threadpinning.jl @@ -0,0 +1,101 @@ +# 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(), ':') + cmd = `taskset -c $cpu_list $(Base.julia_cmd()) --startup-file=no -t $nthreads,0 $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 From 5d4496b63eb9b41d2a439755958d3b44028413e6 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Mon, 30 Nov 2026 14:54:38 -0700 Subject: [PATCH 2/2] Review finding: support pre-1.12 thread flags on PR #810 Julia 1.10/1.11 reject an explicit zero interactive thread count, so the restricted-affinity subprocess never starts and six assertions fail on CI. Use the single-count form on those versions, which already omit interactive threads, and retain the explicit zero on newer Julia. Correct the manual's startup example and record the compatibility rule. Verified in an isolated credential-free sandbox on Julia 1.10.11: all 16 ThreadPinning assertions pass for restricted masks with two and four threads, including repeated pinning and processor/CPU placement. The old flag failure is present in actual-head CI job 141322892787. git diff --check passes. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 6 ++++++ docs/src/threadpinning.md | 3 ++- test/threadpinning.jl | 5 ++++- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 03120cce2..7c226f4be 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1108,3 +1108,9 @@ this section verbatim). Each entry is one bullet starting with `- `. (`mpi_slot_alloc`) rather than copying it afterwards; the copy leaves a GC-managed buffer of the same size behind, which for 16 8 MB slots per region was 989 MiB of GC allocation and 35 collections over 8 regions. + +99. **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. diff --git a/docs/src/threadpinning.md b/docs/src/threadpinning.md index 3baa8ddd5..28647cede 100644 --- a/docs/src/threadpinning.md +++ b/docs/src/threadpinning.md @@ -82,7 +82,8 @@ Dagger.@spawn scope=Dagger.scope(worker=1, thread=2) ThreadPinning.getcpuid() 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,0`), or pin all threads: + 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, diff --git a/test/threadpinning.jl b/test/threadpinning.jl index 99af08eb4..c9deb6874 100644 --- a/test/threadpinning.jl +++ b/test/threadpinning.jl @@ -42,7 +42,10 @@ function run_pinned_child(cpu_list::String, nthreads::Int) script = joinpath(dir, "child.jl") write(script, PINNING_CHILD_SCRIPT) load_path = join(Base.load_path(), ':') - cmd = `taskset -c $cpu_list $(Base.julia_cmd()) --startup-file=no -t $nthreads,0 $script` + # 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))