← Back to Pull requests

KernelInterface 0.3: a tighter back-end contract #800

Closed
unknown closed this pull request without merging on Sep 30, 2026 11:33 UTC
View on GitHub
unknown unknown commented on Sep 28, 2026 08:44 UTC
Author

KernelInterface (KI) is the layer that backends (CUDA.jl, Metal.jl, oneAPI.jl, AMDGPU.jl, OpenCL.jl, and PoCL in this repository) implement, and that KernelAbstractions builds on. Porting those backends to KI 0.2.3 showed that the interface left too much to the individual backends: every backend validated and sized launches itself, and the copies had drifted apart; the same query meant different things on different backends; and the index and sub-group queries were underspecified exactly where the platforms disagree. A kernel written against KI could therefore behave differently depending on where it ran.

KI 0.3 fixes that before the ports merge. It moves launch validation into KI, and writes down the semantics that backends have to implement, so that the testsuite can check them. The design doesn't change: kernels are plain Julia functions, device functions are overlay stubs, and a backend value comes with a task-local device and queue. This is a breaking release without deprecations, since KI has no users outside the backends yet. Each commit is one of the changes below.

KernelInterface owns the launch

Backends used to implement the whole Kernel call, including argument validation and work-group sizing. Now KI implements it, and passes validated 3-D sizes to one method a backend implements:

# before, in every backend
function (obj::KI.Kernel{CUDABackend})(args...; numworkgroups=(), workgroupsize=(), ndrange=(), max_work_group_size=typemax(Int))
    KI.check_launch_args(numworkgroups, workgroupsize, ndrange)
    prod(ndrange) == 0 && return nothing
    blocks, threads = KI.auto_launch_sizes(obj, numworkgroups, workgroupsize, ndrange, max_work_group_size)
    obj.kern(args...; threads, blocks)
    return nothing
end

# after
KI.launch(k::KI.Kernel{CUDABackend}, groups::Dims{3}, items::Dims{3}, args::Vararg{Any,N}; kwargs...) where {N} =
    k.kern(args...; threads = items, blocks = groups, kwargs...)

The launch semantics are documented on KI.Kernel: an ndrange is rounded up to whole work-groups and not masked, a zero anywhere launches nothing, and work-group sizes are checked against the device and the compiled kernel. Invalid launches throw before the driver sees them (here on CUDA):

julia> k(c, a, b; workgroupsize = (1, 1, 128))
ERROR: ArgumentError: Work-group size (1, 1, 128) exceeds the maximum of (1024, 1024, 64) per dimension

julia> k(c, a, b; workgroupsize = (1, 0))
ERROR: ArgumentError: `workgroupsize` must be positive, got (1, 0)

julia> k(c, a, b; ndrange = typemax(Int), workgroupsize = 2)
ERROR: ArgumentError: Launch of (4611686018427387904, 1, 1) work-groups of (2, 1, 1) work-items has more than typemax(Int) work-items in a dimension

(The last one used to reach the backend as a negative global size.) Keywords that KI doesn't know are passed on to KI.launch, so backend options like CUDA's stream or shmem still reach the driver.

Two renames come with this. KI.@kernel is now KI.@launch, since it launches a call like @cuda does, while KA.@kernel defines a kernel. numworkgroups is now numgroups, matching get_num_groups and max_num_groups. KI.@launch also evaluates its backend expression once instead of once per argument, and passes keywords it doesn't know to kernel_function as compiler options.

The limit and the recommendation are separate queries

kernel_max_work_group_size returned an occupancy recommendation on CUDA, AMDGPU and oneAPI, and the hard limit on Metal, OpenCL and PoCL. On an RTX 5080 it returns 768 for a trivial kernel that can be launched with 1024 threads. Two queries replace it:

  • max_work_group_size(kernel) is the largest work-group the compiled kernel can be launched with. Launches are validated against it.

  • launch_configuration(kernel; nitems, max_work_group_size) is the recommended work-group size for a launch of nitems work-items. ndrange launches without a workgroupsize use it, and it falls back to the limit. The problem size is passed separately from the bound, so that heuristics like CUDA's prefer_blocks (more, smaller blocks) don't have to treat the bound as the problem size.
  • max_work_group_dims and max_num_groups are now required. Their typemax(Int) fallbacks meant both "unknown" and "unlimited", and #797 needs them to choose a launch.

    Typed index queries wrap

    The index queries take a result type, e.g. KI.get_global_id(Int32). The docs said the result is "computed in T" and undefined when it doesn't fit, but the backends implemented it as T(x): a checked conversion, which leaves a throw_inexacterror branch in every kernel that uses it. The result is now the exact value modulo T, as with x % T. That costs nothing, and it can be tested: a UInt8 query over 384 work-items has to wrap, where T(x) throws.

    Backends implement the four primitive queries (get_local_id, get_group_id, get_local_size, get_num_groups). get_global_id and get_global_size have fallbacks derived from them for backends without a builtin (CUDA, HIP), and backends that have one (SPIR-V, Metal) should override them.

    Sub-groups

  • Support is a capability: supports_subgroups(backend) and supports_shuffle(backend, T) replace shfl_down_types. The testsuite used to treat a non-empty type list as the flag for sub-group support.

  • sub_group_size(backend) is a guarantee instead of "a reasonable size": kernels from kernel_function run with exactly that width, so host code can pick a Val(N) for a warp-level reduction. A backend that can't guarantee it reports no sub-group support; PoCL now fixes the width at compile time.

  • Partial sub-groups follow OpenCL and SYCL: get_sub_group_size() counts the work-items that are present, and get_num_sub_groups() is cld(items, width). AMDGPU used ÷, reporting 0 sub-groups for a 32-item group on wave64.

  • How work-items map onto sub-groups is unspecified, but each work-item has a unique (sub-group id, lane) pair that doesn't change during the kernel. AMDGPU used activelane(), which renumbers lanes under divergence.

  • shfl_down from a lane that doesn't exist returns an unspecified value (CUDA returns the caller's own value, OpenCL leaves it undefined), and shuffles are not memory fences.

  • The sub-group queries take a result type like the index queries, defaulting to Int. They returned UInt32 on most backends and Int32 on CUDA.
  • Execution, devices and memory

  • Execution is task-local: each task has an active device per backend and a queue on it, which host queries, compilation, allocations, copies and launches use. kernel_function has to store the backend value it was given, so that its options apply (oneAPI dropped its compiler options, and OpenCL its platform, by constructing a new default). A kernel launched after switching devices either works or throws; it never runs on the wrong device.

  • New: device(backend, A), the device that owns A. The device functions are required for backends with more than one device, and the single-device fallbacks now throw when ndevices > 1 instead of answering for the wrong device.

  • Capability defaults are conservative: supports_float64 and supports_atomics now default to false, so that a missing method never claims support.

  • copyto!(backend, dst, src) copies in queue order, returns dst, and throws an ArgumentError for arrays of different lengths. CUDA's implementation copied length(dst) elements from pointer(src) without a check.

  • localmemory and barrier document what memory is shared and which writes become visible. unsafe_free! is an optional hint with a no-op fallback.
  • The contract

    The docs now have a "Semantics" section and a contract table that lists, for each area, the required methods and the optional ones with their fallbacks. The public API is declared with public (Julia 1.11+). There is also a versioning rule: required methods only change in breaking releases, optional methods can be added in any release if their fallback is conservative, and patch releases only add tests for behavior that was already specified. (0.2.3 broke backend CI in a patch release by adding unconditional tests for new obligations.)

    The testsuite's entry point is now Testsuite.testsuite(backend, AT), which takes a backend value, so that backends with options can be tested. It checks that the methods without a fallback are implemented, and covers launch validation, non-square launches, copyto!, local memory, barriers, typed-index wrapping, partial sub-groups and shuffles. Two existing launch tests had formulas that only worked because the group count equaled the group size; the tests now use different sizes in every dimension.

    For KernelAbstractions users

    KernelAbstractions.GPU is removed. It didn't mean GPU hardware: KA's CPU backend is PoCL and subtyped it, so CPU <: GPU. Backends subtype KernelAbstractions.Backend, and code that dispatched on ::GPU should dispatch on ::Backend, on concrete backend types, or on a capability query. This is in the 0.10 changelog.

    Backend ports

    Each backend's KI PR has commits porting it to 0.3 (they get KI 0.3 from this branch through [sources] until it's registered):

    | Backend | PR | KI testsuite |
    |---|---|---|
    | PoCL | this PR | passes |
    | CUDA.jl | JuliaGPU/CUDA.jl#3246 | passes, RTX 5080 and CI |
    | Metal.jl | JuliaGPU/Metal.jl#917 | passes, M1 (Julia 1.10 and 1.12) |
    | oneAPI.jl | JuliaGPU/oneAPI.jl#624 | port in progress |
    | AMDGPU.jl | JuliaGPU/AMDGPU.jl#1047 | port in progress |
    | OpenCL.jl | JuliaGPU/OpenCL.jl#474 | passes, PoCL and NVIDIA (no sub-groups on NVIDIA: the width can't be fixed) |

    Host launch overhead on CUDA (RTX 5080, 1024-element kernel, per launch) is unchanged, except that launches with an explicit size now also query the kernel's thread limit (about 36 ns):

    | | KI 0.2.3 | KI 0.3 |
    |---|---|---|
    | @cuda | 1.68 µs, 256 B | 1.68 µs, 256 B |
    | KI.@launch, explicit sizes | 1.85 µs, 416 B | 1.95 µs, 416 B |
    | KI.@launch, ndrange | 2.03 µs, 416 B | 2.04–2.11 µs, 416 B |
    | compiled Kernel, explicit sizes | 1.42 µs, 160 B | 1.49–1.51 µs, 160 B |
    | compiled Kernel, ndrange | 1.66 µs, 160 B | 1.70–1.74 µs, 160 B |

    KA's Buildkite jobs test the backends' KA 0.10 branches, which still require KI 0.2.3, so they can't be installed together with this PR and soft-fail until those branches are rebased onto the ported KI PRs. The ports above were tested against this branch by hand.

    Not in this PR

    Dynamic local memory, fences and barrier scopes, max_local_memory, more collectives and sub-group size requests can all be added in a minor release; launch options like dynamic local memory can become Kernel keywords without changing KI.launch. #797 and #801, stacked on this PR, use the new contract to launch @kernel kernels on N-d grids with 32-bit indices, and to replace the launch code that every backend copies with one generic implementation in KA.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: maleadt Review duration: 3049m
    All Vouch review confidence checks passed
    Residual risk 0.19 = Change Risk (0.52) × (1 − Review Confidence (0.64)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 70%
    64%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #800"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 64% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 64% · Lower = rushed or shallow review
    64%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 18.7% · Safe to merge
    18.7%