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
12 changes: 12 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,18 @@ merged pull requests, see the [GitHub
releases](https://github.com/JuliaGPU/cuTile.jl/releases).


## v1.3 (unreleased)

*Minor changes*:

- Launching a kernel costs less host time: a launch with two array arguments
takes ~2.4 µs instead of ~4.6 µs on an RTX 5080, and one with nine arrays
~3.1 µs instead of ~9.2 µs. Converting the arguments and looking up the
compiled kernel are now cached; a `TileKernel` obtained from
`cuTile.cufunction` is therefore rebuilt on every lookup, and two lookups of
one kernel compare equal by their `fun` rather than with `===`.


## v1.2 (December 2026)

*Breaking changes*:
Expand Down
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ CompilerCaching = "0.6.1"
DLFP8Types = "0.1.0"
EnumX = "1.0"
GPUArrays = "11, 12"
GPUCompiler = "2.13"
GPUCompiler = "2.18"
GPUToolbox = "3"
IRStructurizer = "0.7, 0.8"
Microfloats = "0.2.6"
Expand Down
122 changes: 87 additions & 35 deletions src/language/types.jl
Original file line number Diff line number Diff line change
Expand Up @@ -198,25 +198,21 @@ function layout_may_alias_internally(sizes::NTuple{N, <:Integer},
end

"""
compute_array_spec(ptr, sizes, strides, elem_size)
array_layout(ptr, sizes, strides) -> Tuple

Compute ArraySpec from array properties.
The layout facts an [`ArraySpec`](@ref) records for an array at `ptr` with
`sizes` and `strides` (in elements), as plain values in the order of
`ArraySpec{N}`'s arguments:

# Arguments
- `ptr`: Base pointer
- `sizes`: Array dimensions
- `strides`: Stride in each dimension (in elements)
- `elem_size`: Size of element type in bytes

# Returns
ArraySpec{N} with:
- `alignment`: Pointer alignment in bytes
- `contiguous`: Whether stride[1] == 1
- `stride_div_by`: Per-dimension stride divisibility (enables vectorized access)
- `shape_div_by`: Per-dimension shape divisibility (eliminates boundary checks)
- `alignment`: pointer alignment in bytes
- `contiguous`: whether `strides[1] == 1`
- `stride_div_by`: per-dimension stride divisibility (enables vectorized access)
- `shape_div_by`: per-dimension shape divisibility (eliminates boundary checks)
- `may_alias_internally`: see [`layout_may_alias_internally`](@ref)
- `singleton`: axes whose size and stride are both one
"""
function compute_array_spec(ptr::Ptr{T}, sizes::NTuple{N, <:Integer},
strides::NTuple{N, <:Integer}) where {T, N}
function array_layout(ptr::Ptr{T}, sizes::NTuple{N, <:Integer},
strides::NTuple{N, <:Integer}) where {T, N}
elem_size = sizeof(T)

# Pointer alignment
Expand All @@ -228,7 +224,7 @@ function compute_array_spec(ptr::Ptr{T}, sizes::NTuple{N, <:Integer},
# Per-dimension stride divisibility
# For stride to enable 16-byte vectorization, stride * elem_size must be divisible by 16
# E.g., for Float32 (4 bytes): stride must be divisible by 4 to get 16-byte alignment
stride_div_by = ntuple(N) do i
stride_div_by = ntuple(Val(N)) do i
sizes[i] == 1 && strides[i] == 1 && return 16 ÷ elem_size
stride_bytes = strides[i] * elem_size
# Check if stride in bytes is 16-byte divisible
Expand All @@ -240,16 +236,25 @@ function compute_array_spec(ptr::Ptr{T}, sizes::NTuple{N, <:Integer},
end

# Per-dimension shape divisibility (for tile boundary optimization)
shape_div_by = ntuple(N) do i
shape_div_by = ntuple(Val(N)) do i
compute_divisibility(sizes[i], 16)
end

singleton = ntuple(i -> sizes[i] == 1 && strides[i] == 1, N)
singleton = ntuple(i -> sizes[i] == 1 && strides[i] == 1, Val(N))

ArraySpec{N}(alignment, contiguous, stride_div_by, shape_div_by,
layout_may_alias_internally(sizes, strides), singleton)
return (alignment, contiguous, stride_div_by, shape_div_by,
layout_may_alias_internally(sizes, strides), singleton)
end

"""
compute_array_spec(ptr, sizes, strides) -> ArraySpec

The [`ArraySpec`](@ref) of an array at `ptr` with `sizes` and `strides`; see
[`array_layout`](@ref).
"""
compute_array_spec(ptr::Ptr, sizes::NTuple{N, <:Integer}, strides::NTuple{N, <:Integer}) where {N} =
ArraySpec{N}(array_layout(ptr, sizes, strides)...)

function validate_axis_order(order, rank::Integer, first_axis::Integer, context::AbstractString)
order isa Tuple || throw(ArgumentError("$context: axis order must be a tuple, got $(typeof(order))"))
length(order) == rank ||
Expand Down Expand Up @@ -323,8 +328,56 @@ function TileArray(ptr::Ptr{T}, sizes::NTuple{N, I}, strides::NTuple{N, I}) wher
# Codegen tells the Tile IR compiler that every stride is non-negative.
all(>=(0), strides) ||
throw(ArgumentError("TileArray strides must be non-negative, got $strides"))
spec = compute_array_spec(ptr, sizes, strides)
TileArray{T, N, I, spec}(ptr, sizes, strides)
new_tilearray(tilearray_type(ptr, sizes, strides), ptr, sizes, strides)
end

# Constructs a `TA`. Dispatching on a `Val` is several times cheaper than calling
# a type that is only known at run time.
new_tilearray(::Val{TA}, ptr, sizes, strides) where {TA} = TA(ptr, sizes, strides)

# `Val(TA)` for the TileArray type `TA` of an array with this layout. Building the
# `ArraySpec` type costs several times the rest of a conversion, which runs on
# every launch, so the types are memoized by their layout facts.
function tilearray_type(ptr::Ptr{T}, sizes::NTuple{N, I}, strides::NTuple{N, I}) where
{T, N, I}
layout = array_layout(ptr, sizes, strides)
memo = tilearray_types(T, Val(N), I)
for (key, TA) in @atomic :acquire memo.entries
key === layout && return TA
end
TA = Val(TileArray{T, N, I, ArraySpec{N}(layout...)})
add_tilearray_type!(memo, layout, TA)
return TA
end

# Untyped, so that the code storing types is compiled once rather than per rank.
mutable struct TileArrayTypes
@atomic entries::Vector{Pair{Any, Val}}
TileArrayTypes() = new(Pair{Any, Val}[])
end

# Enough for the layouts an array type takes in a workload, while keeping the scan
# of a hit short when many layouts are seen.
const TILEARRAY_TYPES_SIZE = 16

# Copy on write, so lookups need no lock, and newest first, dropping the oldest. A
# store that loses a race is dropped, which only costs a later miss.
@noinline function add_tilearray_type!(memo::TileArrayTypes, @nospecialize(layout),
@nospecialize(TA::Val))
entries = @atomic :acquire memo.entries
new_entries = Pair{Any, Val}[layout => TA]
for i in 1:min(length(entries), TILEARRAY_TYPES_SIZE - 1)
push!(new_entries, entries[i])
end
@atomicreplace :acquire_release :monotonic memo.entries entries => new_entries
return
end

# A memo per element type, rank and index type, as a constant in the caller's
# code. A generator that runs again only creates another, empty memo.
@generated function tilearray_types(::Type{T}, ::Val{N}, ::Type{I}) where {T, N, I}
memo = TileArrayTypes()
return :($memo)
end

# Narrowest index type that represents the sizes, the strides, and the linear
Expand Down Expand Up @@ -359,22 +412,21 @@ This method works with any array type that supports:
- `size(arr)` - returns array dimensions
- `strides(arr)` - returns array strides
"""
function TileArray(arr::AbstractArray{T, N}; index=nothing) where {T, N}
arr_sizes = size(arr)
arr_strides = strides(arr)
I = check_indextype(something(index, array_indextype(arr_sizes, arr_strides)))
sizes = NTuple{N, I}(I.(arr_sizes))
strides_val = NTuple{N, I}(I.(arr_strides))
TileArray(device_pointer(arr), sizes, strides_val)
end
TileArray(arr::AbstractArray; index=nothing) = tilearray(arr, arr, index)
TileArray(arr::PermutedDimsArray; index=nothing) = tilearray(arr, parent(arr), index)

function TileArray(arr::PermutedDimsArray{T, N}; index=nothing) where {T, N}
# `arr`, whose memory starts at that of `base`, with index type `index`. Out of
# line, so that it's compiled per array type rather than for every kernel.
@noinline function tilearray(arr::AbstractArray, base::AbstractArray, index)
arr_sizes = size(arr)
arr_strides = strides(arr)
I = check_indextype(something(index, array_indextype(arr_sizes, arr_strides)))
sizes = NTuple{N, I}(I.(arr_sizes))
strides_val = NTuple{N, I}(I.(arr_strides))
TileArray(device_pointer(parent(arr)), sizes, strides_val)
# A branch per index type, so that the conversion is type-stable up to the layout.
if I === Int32
TileArray(device_pointer(base), Int32.(arr_sizes), Int32.(arr_strides))
else
TileArray(device_pointer(base), Int64.(arr_sizes), Int64.(arr_strides))
end
end

# Device arrays hand out device pointer types (e.g. `CuPtr`), which TileArray
Expand Down
93 changes: 58 additions & 35 deletions src/launch.jl
Original file line number Diff line number Diff line change
Expand Up @@ -604,8 +604,8 @@ end
mutable struct TileCompilerResults
cubin::Union{Nothing, Vector{UInt8}}
# linear-scanned by context; usually holds a single entry
kernels::Vector{Tuple{CuContext, Any}}
TileCompilerResults() = new(nothing, Tuple{CuContext, Any}[])
kernels::Vector{Tuple{CuContext, CuFunction}}
TileCompilerResults() = new(nothing, Tuple{CuContext, CuFunction}[])
end

# The results of every job of a kernel, attached by CompilerCaching to the
Expand Down Expand Up @@ -701,8 +701,8 @@ end

# Caller holds job_results_lock.
function find_kernel(res::TileCompilerResults, ctx::CuContext)
for (cached_ctx, kernel) in res.kernels
cached_ctx === ctx && return kernel
for (cached_ctx, fun) in res.kernels
cached_ctx === ctx && return fun
end
return nothing
end
Expand Down Expand Up @@ -736,8 +736,10 @@ target of `(::TileKernel)(args...; blocks, …)` calls. Concrete subtype of
struct TileKernel{F, TT} <: AbstractKernel{F, TT}
f::F
fun::CuFunction
# The `cufunction` options `fun` was compiled with, and the overlap labels
# (see `overlap_labels`) of the alias groups among them.
# The options given to `cufunction`, from which variants for other argument
# types or overlap patterns are compiled (an omitted `sm_arch` then means the
# active device's), and the overlap labels (see `overlap_labels`) of their
# alias groups.
opts::NamedTuple
labels::Vector{Int}
end
Expand Down Expand Up @@ -767,23 +769,44 @@ Mirrors `CUDACore.cufunction` but produces a [`TileKernel`](@ref). Results are
stored on the kernel's Julia `CodeInstance`, so invalidation rides on Julia's
normal CI lifecycle.
"""
function cufunction(@nospecialize(f), tt::Type{<:Tuple}=Tuple{};
function cufunction(f::F, tt::Type{TT}=Tuple{};
sm_arch::Union{VersionNumber, Nothing}=nothing,
opt_level::Union{Int, Nothing}=nothing,
num_ctas::Union{Int, Nothing}=nothing,
occupancy::Union{Int, Nothing}=nothing,
num_worker_warps::Union{Int, Nothing}=nothing,
name::Union{String, Nothing}=nothing,
alias_groups::AliasGroups=())
alias_groups::AliasGroups=()) where {F, TT<:Tuple}
opts = (; sm_arch, opt_level, num_ctas, occupancy, num_worker_warps, name, alias_groups)
# Kernels are looked up in the latest world rather than the caller's, so that a
# redefinition shows on the next launch even from code that is already running.
world = Base.get_world_counter()
fun, labels = GPUCompiler.cached_lookup(KernelLookup(f, tt, opts, world),
Tuple{CuFunction, Vector{Int}}, F, TT,
(context(), world, opts))
return TileKernel{F, TT}(f, fun, opts, labels)
end

# What `cufunction` runs when the kernel isn't cached: a callable struct rather
# than a closure, whose type would differ for every kernel.
struct KernelLookup
f::Any
tt::Type
opts::NamedTuple
world::UInt
end

function (l::KernelLookup)()
(; f, tt, opts, world) = l
# `tileiras` generates architecture-specific code (`sm_100a`), so a kernel
# only runs on the exact architecture it was compiled for. Reflection may
# target other architectures; execution cannot.
device_arch = device_sm_arch()
if sm_arch === nothing
sm_arch = device_arch
elseif sm_arch != device_arch
if opts.sm_arch === nothing
opts = merge(opts, (; sm_arch=device_arch))
elseif opts.sm_arch != device_arch
throw(ArgumentError(
"Cannot execute code compiled for $(format_sm_arch(sm_arch)) on $(device()) " *
"Cannot execute code compiled for $(format_sm_arch(opts.sm_arch)) on $(device()) " *
"(compute capability $device_arch); omit `sm_arch` or pass the device's"))
end

Expand All @@ -794,48 +817,41 @@ function cufunction(@nospecialize(f), tt::Type{<:Tuple}=Tuple{};
# invalidated by any package that defines methods on Base.Compiler hooks
# like `OptimizationParams(::AbstractInterpreter)`. To reuse precompiled
# native code, run the pipeline in the world captured at __init__.
opts = (; sm_arch, opt_level, num_ctas, occupancy, num_worker_warps, name, alias_groups)
invoke_frozen(cufunction_compile, f, tt, argtypes, const_argtypes, opts)::TileKernel{Core.Typeof(f), tt}
fun = invoke_frozen(cufunction_compile, f, argtypes, const_argtypes, opts, world)::CuFunction
labels = groups_to_labels(opts.alias_groups, array_leaves(tt.parameters))
return fun, labels
end

# Inner compilation routine; called via `invoke_frozen` so its method dispatches
# happen in the world captured at __init__, reusing precompiled native code
# even when later-loaded packages would otherwise have invalidated it. It isn't
# specialized on the constant arguments or the options, whose types differ
# with the constants given, which options are set, and the alias grouping.
Base.@nospecializeinfer function cufunction_compile(@nospecialize(f), @nospecialize(tt),
@nospecialize(argtypes),
Base.@nospecializeinfer function cufunction_compile(@nospecialize(f), @nospecialize(argtypes),
@nospecialize(const_argtypes::Union{Tuple, Nothing}),
@nospecialize(opts::NamedTuple))
world = Base.get_world_counter()
@nospecialize(opts::NamedTuple), world::UInt)
job = tile_job(kernel_method_instance(f, argtypes, world), world; const_argtypes, opts...)
res = compile_or_lookup(job)

# Resolve the kernel for the active context. `CuFunction`s are session-local
# Resolve the function for the active context. `CuFunction`s are session-local
# handles, so they live in the results struct's linear cache rather than being
# persisted; the scan is almost always over a single entry.
ctx = context()
cached_kernel = Base.@lock job_results_lock find_kernel(res, ctx)
cached_kernel === nothing || return with_function(cached_kernel, f)
labels = groups_to_labels(opts.alias_groups, array_leaves(tt.parameters))
kernel = TileKernel{Core.Typeof(f), tt}(f, link(job, res), opts, labels)
fun = Base.@lock job_results_lock find_kernel(res, ctx)
fun === nothing || return fun
fun = link(job, res)
# don't cache session-local handles while generating output: the results struct
# is serialized into the package image along with its inference result.
if ccall(:jl_generating_output, Cint, ()) != 1
Base.@lock job_results_lock begin
cached_kernel = find_kernel(res, ctx)
cached_kernel === nothing || return with_function(cached_kernel, f)
push!(res.kernels, (ctx, kernel))
cached = find_kernel(res, ctx)
cached === nothing || return cached
push!(res.kernels, (ctx, fun))
end
end
return kernel
return fun
end

# `k` launching `f` instead of `k.f`. Closures of one type share a compiled
# kernel, but pass their own captured values.
with_function(k::TileKernel{F, TT}, f::F) where {F, TT} =
k.f === f ? k : TileKernel{F, TT}(f, k.fun, k.opts, k.labels)

# Tile IR has a 24-bit grid limit per dimension.
const MAX_GRID_DIM = (1 << 24) - 1

Expand Down Expand Up @@ -1088,9 +1104,16 @@ end

# `@cuda` compiles from the converted arguments' types, so compile for their
# overlap pattern here rather than for disjoint arrays and then a variant.
CUDACore.kernel_compile(call::CUDACore.KernelCall{TileBackend}; kwargs...) =
kernel_compile(call.backend, call.f, Tuple{map(Core.Typeof, call.arguments)...};
kwargs..., alias_groups=alias_groups(call.arguments...))
function CUDACore.kernel_compile(call::CUDACore.KernelCall{TileBackend}; kwargs...)
tt = Tuple{map(Core.Typeof, call.arguments)...}
# The type of a grouping differs with the grouping, so only the common case,
# disjoint arrays, keeps the lookup's type known here.
if all(iszero, overlap_labels(call.arguments...))
return kernel_compile(call.backend, call.f, tt; kwargs..., alias_groups=())
end
return kernel_compile(call.backend, call.f, tt;
kwargs..., alias_groups=alias_groups(call.arguments...))
end


#=============================================================================
Expand Down
14 changes: 13 additions & 1 deletion src/precompile.jl
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,11 @@ import REPL
precompile(alias_groups, Tuple(tt.parameters))
precompile(Tuple{typeof(Core.kwcall), NamedTuple{(:blocks,), Tuple{Int}},
TileKernel{typeof(vadd_1d), tt}, tt.parameters...})
# The kernel lookup `@cuda` makes. Its miss path depends only on which
# options are passed, so this compiles it for every kernel launched
# without any.
precompile(Tuple{typeof(Core.kwcall), NamedTuple{(:alias_groups,), Tuple{Tuple{}}},
typeof(cufunction), typeof(vadd_1d), Type{tt}})
end

# 2D vec_add: multi-dim block IDs and shapes.
Expand Down Expand Up @@ -205,6 +210,13 @@ import REPL

# Launching needs a GPU, which precompilation can't assume, but the launch
# path's compilation entry point is the same for every kernel.
precompile(cufunction_compile, (Any, Any, Any, Union{Tuple, Nothing}, NamedTuple))
precompile(cufunction_compile, (Any, Any, Union{Tuple, Nothing}, NamedTuple, UInt))
precompile(Tuple{KernelLookup})
precompile(add_tilearray_type!, (TileArrayTypes, Any, Val))
precompile(array_leaves, (Core.SimpleVector,))

# Converting the arrays most kernels take.
for T in (Float32, Float16), N in 1:4
precompile(cuTileconvert, (CuArray{T, N, CUDACore.DeviceMemory},))
end
end
Loading