From 4cf47129fa227c012b8ee5de7131fe8d7ddbc18b Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Thu, 3 Dec 2026 13:47:16 +0100 Subject: [PATCH 1/2] Memoize TileArray types by their layout facts Converting an array for a launch took ~550 ns: the index type was only known at run time, so converting the sizes and strides dispatched dynamically, building the `ArraySpec` type from the layout facts (alignment, contiguity, divisibility) cost several times the rest, and calling the resulting type to construct the array cost ~100 ns more. Branch on the index type, compute the layout facts as plain values, and look the `TileArray` type up by those facts in a lock-free memo per element type, rank and index type, as a `Val` to dispatch on rather than a type to call. The memo keeps the 16 most recent layouts, so that a hit stays cheap when many are seen. A conversion now takes ~60 ns and allocates 80 instead of 384 bytes: the result and its arguments, whose type is only known at run time, are boxed. The conversion is now compiled per array type rather than inlined into every kernel's launch code, and precompiled for the common ones, which keeps the first launch from getting slower. --- src/language/types.jl | 122 ++++++++++++++++++++++++++++++------------ src/precompile.jl | 6 +++ test/types.jl | 23 ++++++++ 3 files changed, 116 insertions(+), 35 deletions(-) diff --git a/src/language/types.jl b/src/language/types.jl index 3748b80b..0252f40c 100644 --- a/src/language/types.jl +++ b/src/language/types.jl @@ -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 @@ -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 @@ -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 || @@ -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 @@ -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 diff --git a/src/precompile.jl b/src/precompile.jl index 0a52450b..edf288ea 100644 --- a/src/precompile.jl +++ b/src/precompile.jl @@ -206,5 +206,11 @@ 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(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 diff --git a/test/types.jl b/test/types.jl index d923e67d..01e5b825 100644 --- a/test/types.jl +++ b/test/types.jl @@ -119,6 +119,29 @@ end @test ct.indextype(ct.TileArray(empty)) === Int32 @test_throws ArgumentError ct.TileArray(small; index=UInt32) + # Arrays of one element type, rank and index type still get the spec of their + # own layout, however many conversions came before. + # More layouts than the memo keeps (every alignment and row count gives a + # distinct one), so that the first ones are evicted and then come back. + layouts = [(addr, (rows, 3)) for addr in (128, 192, 160, 144, 136, 132) for rows in (2, 4, 8)] + convert_layout((addr, dims)) = + ct.TileArray(TestDeviceArray(CUDA.CuPtr{Float32}(addr), Int64.(dims), (Int64(1), Int64(dims[1])))) + expected_spec((addr, dims)) = + ct.compute_array_spec(Ptr{Float32}(addr), Int32.(dims), (Int32(1), Int32(dims[1]))) + foreach(convert_layout, layouts) + memo = @atomic ct.tilearray_types(Float32, Val(2), Int32).entries + @test length(memo) == ct.TILEARRAY_TYPES_SIZE + first_layout = ct.array_layout(Ptr{Float32}(128), (Int32(2), Int32(3)), (Int32(1), Int32(2))) + @test !any(entry -> entry.first === first_layout, memo) + for layout in [layouts; layouts[1:3]] + @test ct.array_spec(typeof(convert_layout(layout))) === expected_spec(layout) + end + # Layouts that differ only in whether their elements overlap. + overlapping = TestDeviceArray(CUDA.CuPtr{Float32}(128), (Int64(5), Int64(5)), (Int64(1), Int64(4))) + disjoint = TestDeviceArray(CUDA.CuPtr{Float32}(128), (Int64(5), Int64(5)), (Int64(1), Int64(8))) + @test ct.array_spec(typeof(ct.TileArray(overlapping))).may_alias_internally + @test !ct.array_spec(typeof(ct.TileArray(disjoint))).may_alias_internally + # Codegen assumes non-negative strides (#321); reversed views must not convert. reversed = TestDeviceArray(ptr, (Int64(16), Int64(8)), (Int64(1), -Int64(16))) @test_throws ArgumentError ct.TileArray(reversed) From 9985bddd407ae225281da76780565ca20313e34f Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Thu, 3 Dec 2026 13:53:25 +0100 Subject: [PATCH 2/2] Cache kernel lookups per signature MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every launch looked its kernel up from scratch: the method table lookup in `Base.method_instance`, the job, the CodeInstance holding the compiled results, a lock and the scan for the context's function. That took ~1.6 µs on every launch. Put `GPUCompiler.cached_lookup` in front of it, as CUDACore's `cufunction` does, keyed on the context, the options and the world. The world is the latest one, which the lookup uses, so that a redefinition still shows on the next launch from code that is already running; `cached_lookup` also matches the caller's world, which can only cost a miss. To make the cache a constant per signature, `cufunction` now specializes on the function and argument types; the compilation behind it still doesn't. `@cuda` passes the alias grouping as a constant when no arrays overlap, so that its lookup is resolved statically. The cache must not keep the kernel function, whose captured values come from each launch, so a `TileKernel` is rebuilt around the cached function and its options as given. Two lookups of one kernel share their `fun`, which the tests now compare, but no longer necessarily the rest. For the same reason the per-context function cache now holds the `CuFunction` rather than the first `TileKernel`, which kept the values captured by that launch's closure alive. A hit now takes ~0.1 µs. The precompile workload compiles the lookup's miss path, which is shared by every kernel launched without options, so the first launch doesn't get slower. `cached_lookup` requires GPUCompiler 2.18. --- NEWS.md | 12 +++++ Project.toml | 2 +- src/launch.jl | 93 ++++++++++++++++++++++++-------------- src/precompile.jl | 8 +++- test/device/aliasing.jl | 11 +++++ test/device/compilation.jl | 31 ++++++++++--- 6 files changed, 114 insertions(+), 43 deletions(-) diff --git a/NEWS.md b/NEWS.md index be9955bd..23507e63 100644 --- a/NEWS.md +++ b/NEWS.md @@ -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*: diff --git a/Project.toml b/Project.toml index faa465e0..a4e1fefe 100644 --- a/Project.toml +++ b/Project.toml @@ -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" diff --git a/src/launch.jl b/src/launch.jl index 07fd169d..1f347342 100644 --- a/src/launch.jl +++ b/src/launch.jl @@ -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 @@ -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 @@ -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 @@ -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 @@ -794,8 +817,9 @@ 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 @@ -803,39 +827,31 @@ end # 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 @@ -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 #============================================================================= diff --git a/src/precompile.jl b/src/precompile.jl index edf288ea..719365de 100644 --- a/src/precompile.jl +++ b/src/precompile.jl @@ -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. @@ -205,7 +210,8 @@ 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,)) diff --git a/test/device/aliasing.jl b/test/device/aliasing.jl index b9bcfc26..ab30dfdc 100644 --- a/test/device/aliasing.jl +++ b/test/device/aliasing.jl @@ -48,3 +48,14 @@ end cuTile.launch(store_then_load, 1, x, x, out) @test Array(out) == fill(6f0, 16) end + +@testset "overlap patterns of one signature select their own kernel" begin + x, y = CUDA.zeros(Float32, 16), CUDA.zeros(Float32, 16) + launch(dst, src, out) = @cuda backend=cuTile store_then_load(dst, src, out) + first = launch(x, x, y) # `dst` and `src` overlap + second = launch(x, y, x) # `dst` and `out` overlap + @test first.opts.alias_groups == (((2, ()), (3, ())),) + @test second.opts.alias_groups == (((2, ()), (4, ())),) + @test second.fun !== first.fun + @test launch(x, x, y).fun === first.fun +end diff --git a/test/device/compilation.jl b/test/device/compilation.jl index c51911d2..b2055605 100644 --- a/test/device/compilation.jl +++ b/test/device/compilation.jl @@ -26,12 +26,31 @@ end a = CUDA.zeros(Float32, 16) tt = Tuple{Core.Typeof(ct.cuTileconvert(a))} device_arch = ct.device_sm_arch() - @test ct.cufunction(device_kernel, tt) === ct.cufunction(device_kernel, tt; sm_arch=device_arch) + @test ct.cufunction(device_kernel, tt).fun === + ct.cufunction(device_kernel, tt; sm_arch=device_arch).fun # tileiras generates architecture-specific code, so other targets cannot run here. other_arch = device_arch == v"10.0" ? v"12.0" : v"10.0" @test_throws "Cannot execute" ct.cufunction(device_kernel, tt; sm_arch=other_arch) end +@testset "launch options select their own kernel" begin + function options_kernel(a) + ct.store(a, 1, fill(1.0f0, (16,))) + return + end + a = CUDA.zeros(Float32, 16) + tt = Tuple{Core.Typeof(ct.cuTileconvert(a))} + plain = ct.cufunction(options_kernel, tt) + hinted = ct.cufunction(options_kernel, tt; occupancy=2) + @test hinted.fun !== plain.fun + @test ct.cufunction(options_kernel, tt).fun === plain.fun + @test ct.cufunction(options_kernel, tt; occupancy=2).fun === hinted.fun + # options of the same type, but other values + lookup(occupancy) = ct.cufunction(options_kernel, tt; occupancy).fun + @test lookup(4) !== hinted.fun + @test lookup(2) === hinted.fun +end + @testset "resource usage queries" begin function resource_kernel(a) ct.store(a, 1, fill(1.0f0, (16,))) @@ -59,8 +78,8 @@ end end for _ in 1:8] kernels = fetch.(tasks) kernel = first(kernels) - @test all(k -> k === kernel, kernels) - @test ct.cufunction(context_kernel) === kernel + @test all(k -> k.fun === kernel.fun, kernels) + @test ct.cufunction(context_kernel).fun === kernel.fun kernel() CUDA.synchronize() @@ -70,8 +89,8 @@ end CUDA.CuContext(CUDA.device()) do other_ctx CUDA.context!(other_ctx) do other_kernel = ct.cufunction(context_kernel) - @test other_kernel !== kernel - @test ct.cufunction(context_kernel) === other_kernel + @test other_kernel.fun !== kernel.fun + @test ct.cufunction(context_kernel).fun === other_kernel.fun stream = CUDA.CuStream() try other_kernel(; stream) @@ -82,7 +101,7 @@ end end end end - @test ct.cufunction(context_kernel) === kernel + @test ct.cufunction(context_kernel).fun === kernel.fun @test ct.compile_or_lookup(job).cubin === cubin end end