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
3 changes: 3 additions & 0 deletions Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ SPIRVIntrinsics = "71d1d633-e7e8-4a92-83a1-de8814b09ba8"
SPIRV_LLVM_Backend_jll = "4376b9bf-cff8-51b6-bb48-39421dff0d0c"
SPIRV_Tools_jll = "6ac6d60f-d740-5983-97d7-a4482c0689f4"
StaticArraysCore = "1e83bf80-4336-4d27-bf5d-d5a4f845583c"
ThreadTeams = "100744f9-5cbb-42a9-938e-f15a20f71997"
UnsafeAtomics = "013be700-e6cd-48c3-b4a1-df204f14c38f"
pocl_standalone_jll = "54f56a70-6062-5590-a942-1226658f6c83"

Expand Down Expand Up @@ -67,6 +68,8 @@ SPIRV_Tools_jll = "2024.4, 2025.1"
SparseArrays = "<0.0.1, 1.6"
StaticArrays = "1.5"
StaticArraysCore = "1"
# 1.3: `foreach_range` steals from nearby threads first
ThreadTeams = "1.4"
UnsafeAtomics = "0.4"
julia = "1.10"
oneAPI = "2"
Expand Down
19 changes: 8 additions & 11 deletions docs/src/examples/numa_aware.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,21 @@ $(read(path, String))

**Important remarks:**

The `CPU` backend runs kernels with [PoCL](https://portablecl.org) on PoCL's own threads, not on Julia's. That determines how to apply the usual advice for NUMA systems:
The `CPU` backend runs kernels on Julia's threads (see [`CPU`](@ref)). For NUMA locality:

1) Pin the threads that run the kernels. Set PoCL's `POCL_AFFINITY=1` environment variable before the backend is first used. It pins each of PoCL's threads to one of the CPUs the process may run on (respecting e.g. `taskset`), a core of its own first, spread over the NUMA domains, so that fewer threads than cores still use the memory bandwidth of every domain. Tools that pin Julia's threads, like [ThreadPinning.jl](https://github.com/carstenbauer/ThreadPinning.jl), don't affect the threads that run the kernels. Without pinning, the operating system moves the threads around, and where they touch the memory first says little about where they run later.
1) Pin Julia's threads before the first launch with [ThreadPinning.jl](https://github.com/carstenbauer/ThreadPinning.jl). `pinthreads(:numa)` spreads threads across NUMA domains; `pinthreads(:cores)` follows the machine's topology. Both pin only the default pool. Start Julia with `-t N,0` or pass `threadpool = :all` to pin small launches on the launching thread too. Without pinning, threads can migrate away from the memory they first touched.
2) Choose the number of threads with `julia -t N` or the `JULIA_KA_CPU_THREADS` environment variable; see [`CPU`](@ref).
3) Initialize your data in parallel(!), with a kernel. Under the ["NUMA first-touch policy"](https://queue.acm.org/detail.cfm?id=2513149#:~:text=This%20is%20called%20the%20first,policy%20associated%20with%20a%20task.) a page of memory is placed in the memory domain of the thread that first writes to it. `fill!` writes from the calling thread, which places all the memory in that thread's domain. The example instead allocates with `KernelAbstractions.allocate` and writes the initial values with a kernel (`init = :parallel`). PoCL gives each thread a contiguous block of a kernel's workgroups, so a later kernel with as many workgroups mostly works on each part of the array from the thread that touched it first. `KernelAbstractions.zeros(backend, dtype, N)` and `KernelAbstractions.ones` initialize with a kernel too, for arrays of bits types of at least 1 MiB; smaller arrays, and arrays of other types, are filled from the calling thread.

This needs KernelAbstractions 0.10.2 or later, which avoids the masked memory accesses that made kernels slow on some AMD CPUs, and the `pocl_standalone_jll` 7.2.3+1 or later that it installs, whose PoCL schedules workgroups and pins threads this way.
3) Initialize data with a parallel kernel. Under the [NUMA first-touch policy](https://queue.acm.org/detail.cfm?id=2513149#:~:text=This%20is%20called%20the%20first,policy%20associated%20with%20a%20task.), a memory page belongs to the domain of the thread that first writes it. `fill!` places pages in the calling thread's domain. The example uses `KernelAbstractions.allocate` followed by an initialization kernel (`init = :parallel`). Launches with as many workgroups start each block of them on the same thread, as `Threads.@threads :static` does, so later kernels mostly work on the data their thread touched first. `KernelAbstractions.zeros(backend, dtype, N)` and `KernelAbstractions.ones` also use a kernel for arrays of bits types of at least 1 MiB; other arrays are filled on the calling thread.

**Demonstration:**

On a system with two AMD EPYC 7502 (2 × 32 cores, 2 NUMA domains), the example (`N = 512_000_000`, workgroups of 1024) gets the following memory bandwidth, in GB/s:
On a system with two AMD EPYC 7502 (2 × 32 cores, 2 NUMA domains), the example (`N = 512_000_000`, workgroups of 1024), started with `-t T,0` for each thread count `T`, gets the following memory bandwidth, in GB/s:

| threads | initialization | `POCL_AFFINITY=1` | `POCL_AFFINITY` unset |
| threads | initialization | `pinthreads(:numa)` | `pinthreads(:cores)` |
|--:|---|--:|--:|
| 64 | `init = :parallel`, or `zeros` and `ones` | 242 | 130–155 |
| 64 | `init = :serial` | 142 | 137 |
| 32 | `init = :parallel`, or `zeros` and `ones` | 157 | 121–135 |
| 32 | `init = :serial` | 124 | 121–139 |
| 64 | `init = :parallel` | 243 | 243 |
| 64 | `zeros` and `ones` | 241 | 242 |
| 32 | `init = :parallel` | 158 | |

A plain `Threads.@threads :static` loop with its threads pinned by ThreadPinning.jl gets 240 GB/s with 64 threads. Initializing serially puts all the memory in one domain. Without pinning, the threads that touch the memory first aren't reliably the ones that work on it later, and the numbers vary from run to run with where the operating system places the threads.

Expand Down
19 changes: 19 additions & 0 deletions docs/src/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,25 @@ end
workgroup, on every backend. `@groupreduce` uses sub-groups internally where the backend
can shuffle the values. See [Reductions and scans](@ref group_collectives).

#### Unreleased
- The `CPU` backend runs kernels on Julia's threads instead of PoCL's, through PoCL's
`cl_pocl_host_kernel` extension (`pocl_standalone_jll` 7.2.3 or later). On a 4-core x86
machine, a launch costs about 0.15 µs on the launching task and 1 µs on several threads,
down from 5 µs. Small launches, and launches while the threads are busy (e.g. from a
`Threads.@threads` loop), run on the launching task alone. A launch doesn't yield while
its kernel runs. See [`CPU`](@ref).
- Launches with as many workgroups start each block of them on the thread on which a
`Threads.@threads :static` loop over as many iterations runs it, so data stays in that
thread's cache and NUMA node. Pin Julia's threads before the first launch, e.g. with
ThreadPinning.jl; `POCL_AFFINITY` only applies to the few kernels that still run on
PoCL's threads.
- On the `CPU` backend, work-items no longer check whether they are inside the range when
the workgroups cover it exactly, and otherwise only those of partial workgroups do (from
a kernel's second launch with partial workgroups on, so that a kernel launched once is
compiled once). This lets PoCL vectorize kernels better: an axpy over 10⁵ elements on one
thread took about 15% longer than a serial loop, rather than 3× (x86) to 7× (Apple M1) as
long. `muladd` is computed with fused multiply-adds on CPUs that have them.

## Semantic differences

### To CUDA.jl/AMDGPU.jl
Expand Down
7 changes: 5 additions & 2 deletions docs/src/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,8 +195,11 @@ function exchange_and_compute!(backend, A, B)
end
```

Waiting on a backend, whether with [`synchronize`](@ref) or at the end of a spawned task,
yields to the Julia scheduler, so other tasks keep making progress while a kernel runs.
Waiting on a GPU backend, whether with [`synchronize`](@ref) or at the end of a spawned
task, yields to the Julia scheduler, so other tasks keep making progress while a kernel runs.
The `CPU` backend runs every launch to completion before it returns, without yielding;
other tasks, timers and I/O run after launches on several threads and after long ones (see
[`CPU`](@ref)).

### Which device a task runs on

Expand Down
4 changes: 2 additions & 2 deletions examples/numa_aware.jl
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# EXCLUDE FROM TESTING
# Run with `POCL_AFFINITY=1` to pin the threads that run the kernels, e.g.
# POCL_AFFINITY=1 julia -t 128 examples/numa_aware.jl
# pin Julia's threads before the first launch:
# julia -t 128,0 -e 'using ThreadPinning; pinthreads(:numa); include("examples/numa_aware.jl")'
using BenchmarkTools
using KernelAbstractions

Expand Down
44 changes: 36 additions & 8 deletions src/KernelAbstractions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -788,14 +788,42 @@ synchronize(CPU())

# Threads

Kernels run on as many threads as Julia's default thread pool has (`julia -t N`), up to the
number of hardware threads. These are POCL's own threads, so launching a kernel doesn't
occupy Julia's. To use a different number, set the `JULIA_KA_CPU_THREADS` environment
variable before the backend is first used, e.g., `JULIA_KA_CPU_THREADS=8 julia -t1`. POCL's
own variables (e.g., `POCL_CPU_MAX_CU_COUNT`) are respected too, and can also raise the
number above the number of hardware threads, but they also affect other users of POCL, like
OpenCL.jl. The device reports the number as its compute units:
`KernelAbstractions.POCL.device().max_compute_units`.
Kernels run on Julia's default thread pool (`julia -t N`), up to the number of hardware
threads. A launch splits its workgroups into blocks as `Threads.@threads :static` splits a
loop: block `k` starts on the `k`-th thread of the pool, whichever thread launches, and the
launching task runs the block of its own thread.

Launches of up to 8192 work-items run on the launching task alone, unless the kernel's last
two launches over as many workgroups would each have taken 4 µs or more on one thread. So
do launches from finalizers, and launches while the threads are busy: from a
`Threads.@threads` loop, from a kernel, or while another task's launch uses them. On Julia
1.12 and later, such a launch from the interactive thread (`julia -t N,1`) runs there.

A launch doesn't yield while its kernel runs, and delivers interrupts (`^C`) once it is
done. Before Julia 1.14, `^C` goes to whatever runs on thread 1, so this only protects
launches from there (e.g. the main task). Other tasks, timers and I/O run after launches on several threads, and after
launches of a kernel whose last launch took 50 µs or more.

Since launches with as many workgroups start each block on the same thread, data that a
`Threads.@threads :static` loop or such a launch wrote first is usually in that thread's
cache and NUMA node. Workgroups still move: a block whose thread starts late runs on the
launching thread, and when the number of workgroups changed or the last launch took 50 µs
or more, threads that are done take workgroups from the others, nearby threads first (on
Linux, with pinned threads).

Pin the threads before the first launch, e.g. with ThreadPinning.jl: `pinthreads(:numa)`
or `pinthreads(:cores)`. It pins only the default pool, so start Julia with `julia -t N,0`,
or pass `threadpool = :all`, to also pin launches on the launching task.

Kernels with an explicit workgroup size that may need more than 1 MiB of stack, and
kernels that PoCL can't run on Julia's threads, run on PoCL's own threads instead; pin
those with `POCL_AFFINITY=1`.

To use fewer threads, set `JULIA_KA_CPU_THREADS` before the backend is first used:
launches then use the first threads of the default pool, with larger blocks. PoCL's
variables (e.g. `POCL_CPU_MAX_CU_COUNT`) work too, but also affect other users of PoCL,
like OpenCL.jl. None of them raises the count above the pool's size;
`KernelAbstractions.KernelInterface.multiprocessor_count(CPU())` returns the count used.

# Atomics

Expand Down
47 changes: 43 additions & 4 deletions src/backend_launch.jl
Original file line number Diff line number Diff line change
Expand Up @@ -180,10 +180,21 @@ function launch_kernel(
end
ctx, groups, items = launch_geometry(sizes_only(obj), launch, subgroups, ndrange, iterspace, ctx, threads)

# the kernel's limits aren't the device's, and the workgroups tuned for them don't cover
# the ndrange: launch the checked kernel instead
if unchecked && tuned && !covers(range, ctx)
return launch_kernel(obj, launch, subgroups, ndrange, _workgroupsize, iterspace, args, true)
# partial workgroups need bounds checks. if kernel-specific tuning introduced them
# unexpectedly, relaunch checked. otherwise, split-capable backends can run full
# workgroups unchecked.
if !checked && skip_bounds_check(b) && bounded(range, iterspace) && !covers(range, ctx)
unchecked &&
return launch_kernel(obj, launch, subgroups, ndrange, _workgroupsize, iterspace, args, true)
extent = split_extent(size(cartesian(range)), items)
if extent !== nothing && split_launch(b, launch, kernel)
full_tt = Base.compilerbarrier(:type, without_bounds_check(tt))::Type

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dark magic

full = kernel_function_as(b, obj.f, full_tt, tt; compiler_options(obj)...)
if prod(items) <= KI.max_work_group_size(full)
launch_split(full, kernel, extent, groups, items, prepend(ctx, kernel_args))
return nothing
end
end
end

KI.check_work_group_size(kernel, items)
Expand All @@ -206,6 +217,34 @@ specializing on `compiled_tt`.
"""
function kernel_function_as end

"""
split_launch(backend, launch, checked)::Bool

Whether to run full workgroups unchecked and partial ones with `checked`, using
[`launch_split`](@ref). A backend may decline early launches to avoid compiling an unchecked
variant for kernels used only once. Only called if `skip_bounds_check(backend)`.
"""
split_launch(backend, launch, checked) = false

# map `dims` to the launch grid, or return `nothing` if partial workgroups aren't confined
# to its edges. beyond 3 dimensions, `nd_grid` folds later dimensions into the third,
# placing partial third-dimension workgroups inside the grid.
function split_extent(dims::Dims{N}, items::Dims{3}) where {N}
N > 3 && dims[3] % items[3] != 0 && return nothing
return KI.pad3(nd_grid(dims))
end

"""
launch_split(kernel, checked, extent, groups, items, args)

Run `groups` workgroups of `items` work-items as one launch. Workgroups entirely within
`extent` (the ndrange mapped by `split_extent`) use the unchecked `kernel`; the rest use
`checked`. Both take `args` with the same layout (see `kernel_function_as`). A backend may
fall back to `checked` for every workgroup. Only called if [`split_launch`](@ref) returned
`true`.
"""
function launch_split end

"""
expected_workgroupsize(backend, nitems)

Expand Down
Loading
Loading