diff --git a/NEWS.md b/NEWS.md index 23507e63..2271e43a 100644 --- a/NEWS.md +++ b/NEWS.md @@ -11,13 +11,25 @@ releases](https://github.com/JuliaGPU/cuTile.jl/releases). *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 + takes ~1.9 µs instead of ~4.6 µs on an RTX 5080, and one with nine arrays + ~2.4 µ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.1 (unreleased) + +*Bug fixes*: + +- A `@cuda backend=cuTile stream=s` or `cuTile.launch(...; stream=s)` launch is + ordered after earlier work on its `CuArray` arguments (and strided views of + them) on other streams, and later work on them waits for it, like a CUDA.jl + launch. Before, a launch on a stream other than the task's could read data + that was still being written, or have its results read before it finished. + cuTile.jl now requires CUDACore 6.5. + + ## v1.2 (December 2026) *Breaking changes*: diff --git a/Project.toml b/Project.toml index a4e1fefe..c86f4656 100644 --- a/Project.toml +++ b/Project.toml @@ -34,7 +34,7 @@ MicrofloatsExt = "Microfloats" [compat] Adapt = "4.4" BFloat16s = "0.6" -CUDACore = "6.3" +CUDACore = "6.5" CUDA_Compiler_jll = "0.6.3" CompilerCaching = "0.6.1" DLFP8Types = "0.1.0" diff --git a/src/broadcast.jl b/src/broadcast.jl index 4c235390..d582bba3 100644 --- a/src/broadcast.jl +++ b/src/broadcast.jl @@ -58,51 +58,114 @@ struct Extruded{K, A} end Extruded{K}(x::A) where {K, A} = Extruded{K, A}(x) -# Counterpart of `Base.Broadcast.preprocess`: convert the array leaves of a -# Broadcasted tree into Extruded TileArrays, given the converted destination -# and its rank. Leaves copied to unalias them from the destination are pushed -# to `copies`, which the caller keeps alive until the launch. -preprocess(t::Tiled, dest, copies, rank::Val) = preprocess(parent(t), dest, copies, rank) -preprocess(arr::AbstractArray{<:Any, 0}, dest, copies, rank::Val) = - preprocess(reshape(arr, 1), dest, copies, rank) -function preprocess(arr::AbstractArray, dest, copies, ::Val{N}) where N - keeps = ntuple(d -> size(arr, d) != 1, Val(N)) - # The typeassert rejects leaves without device storage, like ranges, - # which `cuTileconvert` passes through unchanged. - leaf = cuTileconvert(arr)::AbstractTileArray - # Like `Base.Broadcast.broadcast_unalias`: blocks run in any order, so a - # leaf sharing memory with the destination, other than the destination - # itself, could be read after another block stored to it. Copy it first. - # Overlap is judged by address range, as at launch (`overlap_labels`). - if leaf != dest && !all(iszero, overlap_labels(dest, leaf)) - push!(copies, copy(arr)) - leaf = cuTileconvert(copies[end])::AbstractTileArray +# The array leaves of a Broadcasted tree, in depth-first order: the arrays that +# become the kernel's `TileArray`s. Their types are known statically, unlike +# those of their converted forms, which record the arrays' layouts. +broadcast_leaves(t::Tiled) = broadcast_leaves(parent(t)) +broadcast_leaves(arr::AbstractArray) = (arr,) +broadcast_leaves(arr::AbstractArray{<:Any, 0}) = (reshape(arr, 1),) +broadcast_leaves(bc::Broadcasted) = _broadcast_leaves(bc.args...) +broadcast_leaves(x) = () +_broadcast_leaves() = () +_broadcast_leaves(x, xs...) = (broadcast_leaves(x)..., _broadcast_leaves(xs...)...) + +# Whether the converted array leaf `leaf` has to be copied before it can be read +# while the converted destination `dest` is written. Like +# `Base.Broadcast.broadcast_unalias`: blocks run in any order, so a leaf sharing +# memory with the destination, other than the destination itself, could be read +# after another block stored to it. Overlap is judged by address range, as at +# launch (`overlap_labels`). +needs_copy(dest, leaf) = leaf != dest && !all(iszero, overlap_labels(dest, leaf)) + +# Counterpart of `Base.Broadcast.preprocess`: the kernel's Broadcasted tree, +# which is `bc` with its array leaves (see `broadcast_leaves`) replaced by +# their converted forms `leaves`, extruded along the dimensions that `keeps` +# flags for each, and its functions and other leaves converted with adaptor +# `to`, as Adapt converts a Broadcasted. +@generated extrude(bc::Broadcasted, leaves::Tuple, ::Val{keeps}, to) where {keeps} = + extrude_expr(bc, :bc, keeps, Ref(0)) + +# `bc` with the types of its arguments those of their values, as `extrude` +# reads them: a Broadcasted constructed with abstract argument types could +# otherwise hide array leaves. Static for the trees `broadcasted` builds. +retype(bc::Broadcasted) = Broadcasted{Nothing}(bc.f, map(retype, bc.args), nothing) +retype(x) = x + +function extrude_expr(@nospecialize(T), @nospecialize(ex), @nospecialize(keeps), leaf::Ref{Int}) + if T <: Broadcasted + A = fieldtype(T, :args) + # A loop rather than a comprehension, whose closure would be compiled + # for every tree. + args = Any[] + for i in 1:fieldcount(A) + push!(args, extrude_expr(fieldtype(A, i), :($ex.args[$i]), keeps, leaf)) + end + return :(Broadcasted{Nothing}(adapt(to, $ex.f), ($(args...),), nothing)) + elseif T <: Union{Tiled, AbstractArray} + i = leaf[] += 1 + return :(Extruded{$(keeps[i])}(leaves[$i])) + else + return :(adapt(to, $ex)) end - Extruded{keeps}(leaf) end -preprocess(bc::Broadcasted, dest, copies, rank::Val) = - Broadcasted{Nothing}(bc.f, map(arg -> preprocess(arg, dest, copies, rank), bc.args), nothing) -preprocess(x, dest, copies, rank::Val) = x function _tiled_broadcast!(dest::AbstractArray{T,N}, bc::Broadcasted) where {T, N} # Match Base semantics: size-1 dimensions expand, other mismatches throw. Base.Broadcast.check_broadcast_axes(axes(dest), bc.args...) isempty(dest) && return - dest_ta = cuTileconvert(dest) - copies = Any[] - tiled_bc = preprocess(bc, dest_ta, copies, Val(N)) - ts = _compute_tile_sizes(size(dest)) grid = ntuple(i -> cld(size(dest, i), ts[i]), N) launch_grid, overflow = _flatten_grid(grid) - GC.@preserve copies launch(broadcast_kernel, launch_grid, dest_ta, tiled_bc, - Constant(ts), Constant(overflow)) + leaves = broadcast_leaves(bc) + keeps = map(leaf -> ntuple(d -> size(leaf, d) != 1, Val(N)), leaves) + statics = (keeps, ts, overflow) + copies = GC.@preserve dest bc leaves begin + convert_and_broadcast(Managed[], statics, launch_grid, bc, dest, leaves...) + end + copies === nothing && return + # Some leaves overlap the destination: launch with copies of them instead. + leaves = map((leaf, copy_leaf) -> copy_leaf ? copy(leaf) : leaf, leaves, copies) + GC.@preserve dest bc leaves begin + convert_and_broadcast(Managed[], statics, launch_grid, bc, dest, leaves...)::Nothing + end + return +end + +# Converts the destination and each array leaf to a separate argument, so that +# the call below dispatches on their types rather than the tree being built +# from values whose types are only known at run time. The memory of the +# converted arrays is recorded in `managed` for the launch to acquire. The +# values that the kernel is specialized on, `statics`, go in one type, as +# building each of their types at run time costs more. +@generated function convert_and_broadcast(managed, statics, grid, bc, dest, + leaves::Vararg{Any, L}) where {L} + # The typeassert rejects leaves without device storage, like ranges, which + # the adaptor passes through unchanged. + converted = [:(adapt(to, leaves[$i])::AbstractTileArray) for i in 1:L] + quote + to = KernelAdaptor(managed) + broadcast_converted(managed, Val(statics), grid, bc, adapt(to, dest), + $(converted...)) + end +end + +# Launch the broadcast `bc` into `dest` with converted array leaves `leaves`. +# Returns which leaves need to be copied first, if any, without launching. +@noinline function broadcast_converted(managed, ::Val{statics}, grid, bc, dest, + leaves::Vararg{Any, L}) where {statics, L} + keeps, ts, overflow = statics + copies = map(leaf -> needs_copy(dest, leaf), leaves) + any(copies) && return copies + tiled_bc = extrude(retype(bc), leaves, Val(keeps), KernelAdaptor(managed)) + compile_and_launch(TileBackend(), managed, Val(true), (; blocks=grid), (;), + broadcast_kernel, dest, tiled_bc, Constant(ts), Constant(overflow)) + return nothing end # The kernel operates on tiles of rank >= 1, so run 0-dim broadcasts (both -# destinations, above, and leaves, in `preprocess`) as 1-element vectors. +# destinations, above, and leaves, in `broadcast_leaves`) as 1-element vectors. _tiled_broadcast!(dest::AbstractArray{<:Any,0}, bc::Broadcasted) = _tiled_broadcast!(reshape(dest, 1), bc) diff --git a/src/language/types.jl b/src/language/types.jl index 0252f40c..58580f1a 100644 --- a/src/language/types.jl +++ b/src/language/types.jl @@ -328,12 +328,13 @@ 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")) - new_tilearray(tilearray_type(ptr, sizes, strides), 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) +# a type that is only known at run time. The fields are passed as one value, +# which the dynamic call boxes once rather than per field. +new_tilearray(::Val{TA}, fields::Tuple) where {TA} = TA(fields...) # `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 @@ -365,7 +366,7 @@ const TILEARRAY_TYPES_SIZE = 16 @noinline function add_tilearray_type!(memo::TileArrayTypes, @nospecialize(layout), @nospecialize(TA::Val)) entries = @atomic :acquire memo.entries - new_entries = Pair{Any, Val}[layout => TA] + new_entries = Pair{Any, Val}[Pair{Any, Val}(layout, TA)] for i in 1:min(length(entries), TILEARRAY_TYPES_SIZE - 1) push!(new_entries, entries[i]) end @@ -415,17 +416,19 @@ This method works with any array type that supports: TileArray(arr::AbstractArray; index=nothing) = tilearray(arr, arr, index) TileArray(arr::PermutedDimsArray; index=nothing) = tilearray(arr, parent(arr), index) -# `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`, whose memory starts at that of `base` (at `ptr`), 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, + ptr::Ptr=device_pointer(base)) arr_sizes = size(arr) arr_strides = strides(arr) I = check_indextype(something(index, array_indextype(arr_sizes, arr_strides))) # 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)) + TileArray(ptr, Int32.(arr_sizes), Int32.(arr_strides)) else - TileArray(device_pointer(base), Int64.(arr_sizes), Int64.(arr_strides)) + TileArray(ptr, Int64.(arr_sizes), Int64.(arr_strides)) end end diff --git a/src/launch.jl b/src/launch.jl index 1f347342..ee70b3bc 100644 --- a/src/launch.jl +++ b/src/launch.jl @@ -6,7 +6,7 @@ # per job configuration on the kernel's inference result. using ObjectFile: ObjectFile, readmeta, Sections -using CUDACore: CUDACore, CuArray, CuModule, CuFunction, CuContext, context, cudacall, +using CUDACore: CUDACore, CuArray, CuPtr, Managed, CuModule, CuFunction, CuContext, context, cudacall, device, capability, AbstractBackend, AbstractKernel, kernel_convert, kernel_compile using CUDA_Compiler_jll @@ -22,13 +22,21 @@ using Adapt: Adapt, adapt `Adapt.jl` adaptor used to convert host-side launch arguments into their kernel-side counterparts. `AbstractArray`s become `TileArray`s; `Type` values become `Constant`s. User-defined structs containing arrays compose -naturally via `Adapt.adapt_structure`. +naturally via `Adapt.adapt_structure`. A rule that converts an array itself +should do so with `Adapt.adapt(to, array)`, so that a launch knows which +memory the kernel uses. This is the cuTile analogue of `CUDACore.KernelAdaptor`. """ -struct KernelAdaptor end +struct KernelAdaptor + # The memory of the converted arrays, for a launch to acquire on its stream + # (see `CUDACore.with_managed`); without it, conversion takes the pointers + # for use on the task's stream. + managed::Union{Nothing, Vector{Managed}} +end +KernelAdaptor() = KernelAdaptor(nothing) -Adapt.adapt_storage(::KernelAdaptor, arr::AbstractArray) = TileArray(arr) +Adapt.adapt_storage(to::KernelAdaptor, arr::AbstractArray) = kernel_tilearray(arr, arr, to.managed) Adapt.adapt_storage(::KernelAdaptor, t::Type) = Constant(t) # Adapt's defaults for `PermutedDimsArray` and `SubArray` recurse by @@ -36,8 +44,32 @@ Adapt.adapt_storage(::KernelAdaptor, t::Type) = Constant(t) # pattern because `TileArray` isn't `<:AbstractArray` — strided-wrapper # state is absorbed into its `sizes`/`strides` fields directly. Short-circuit # the recursion so the whole wrapper becomes a single TileArray. -Adapt.adapt_structure(::KernelAdaptor, arr::PermutedDimsArray) = TileArray(arr) -Adapt.adapt_structure(::KernelAdaptor, arr::SubArray) = TileArray(arr) +Adapt.adapt_structure(to::KernelAdaptor, arr::PermutedDimsArray) = + kernel_tilearray(arr, parent(arr), to.managed) +Adapt.adapt_structure(to::KernelAdaptor, arr::SubArray) = kernel_tilearray(arr, arr, to.managed) + +kernel_tilearray(arr, base, ::Nothing) = tilearray(arr, base, nothing) +kernel_tilearray(arr, base, managed::Vector{Managed}) = + tilearray(arr, base, nothing, managed_pointer(base, managed)) + +# The device address of `arr`, whose memory is recorded in `managed` rather than +# taken for use on the task's stream: like CUDACore's conversion of a `CuArray` +# for its own kernels, so that the launch orders the kernel after earlier uses +# of the memory on other streams. Other arrays take their pointer as usual. +function managed_pointer(arr::CuArray{T}, managed::Vector{Managed}) where {T} + memory = CUDACore.check_capture(arr.data)[] + push!(managed, memory) + return reinterpret(Ptr{T}, convert(CuPtr{T}, memory.mem) + arr.offset) +end +# (as `Base.unsafe_convert(::Type{CuPtr{T}}, ::SubArray)` does for these views) +managed_pointer(V::SubArray{T, N, <:CuArray, <:Tuple{Vararg{Base.RangeIndex}}}, + managed::Vector{Managed}) where {T, N} = + managed_pointer(parent(V), managed) + Base._memory_offset(V.parent, map(first, V.indices)...) +managed_pointer(V::SubArray{T, N, <:CuArray, + <:Tuple{Vararg{Union{Base.RangeIndex, Base.ReshapedUnitRange}}}}, + managed::Vector{Managed}) where {T, N} = + managed_pointer(parent(V), managed) + (Base.first_index(V) - 1) * CUDACore.aligned_sizeof(T) +managed_pointer(arr::AbstractArray, ::Vector{Managed}) = device_pointer(arr) """ cuTileconvert(x) @@ -76,6 +108,8 @@ The default cuTile backend, looked up by `@cuda backend=cuTile`. Returns a DefaultBackend() = TileBackend() CUDACore.kernel_convert(::TileBackend, x) = cuTileconvert(x) +CUDACore.kernel_convert(::TileBackend, x, managed::Vector{Managed}) = + adapt(KernelAdaptor(managed), x) CUDACore.kernel_compile(::TileBackend, f::F, tt::TT=Tuple{}; kwargs...) where {F,TT} = cufunction(f, tt; kwargs...) @@ -778,10 +812,23 @@ function cufunction(f::F, tt::Type{TT}=Tuple{}; name::Union{String, Nothing}=nothing, alias_groups::AliasGroups=()) where {F, TT<:Tuple} opts = (; sm_arch, opt_level, num_ctas, occupancy, num_worker_warps, name, alias_groups) + return lookup_kernel(f, tt, opts) +end + +# The options of `cufunction`, as it passes them to `lookup_kernel`. +kernel_options(; 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=()) = + (; sm_arch, opt_level, num_ctas, occupancy, num_worker_warps, name, alias_groups) + +# Inlined, so that a launch compiles no method for this per signature. +@inline function lookup_kernel(f::F, ::Type{TT}, opts::NamedTuple) where {F, TT<:Tuple} # 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), + 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) @@ -891,23 +938,8 @@ end # `@cuda` passes `convert=Val(false)` because it converted the arguments # already. Arguments are always taken as converted, so direct `kernel(args...)` # calls must convert them first. -# -# `@generated` so that flattening the arguments folds to a direct `cudacall`, as -# in CUDACore's `HostKernel`; flattening at runtime costs ~400 ns per launch, -# even for trivial kernels. -@generated function (k::TileKernel{F})(args::Vararg{Any, N}; blocks=1, threads=1, - convert=Val(false), kwargs...) where {F, N} - arg_exprs = Any[] - type_exprs = Any[] - # The kernel function comes first: the values it captures are parameters too. - flatten_params!(arg_exprs, type_exprs, F, :(k.f)) - for i in 1:N - flatten_params!(arg_exprs, type_exprs, args[i], :(args[$i])) - end - # The implicit KernelState comes last, as in codegen. - push!(arg_exprs, :(state.seed)) - push!(type_exprs, UInt32) - +@generated function (k::TileKernel{F})(args::Vararg{Any, N}; convert=Val(false), + kwargs...) where {F, N} leaves = Tuple(array_leaves(args)) # The kernel assumes the argument types and the overlap pattern it was # compiled for. Another one (from a `launch=false` kernel or a rebound @@ -922,22 +954,56 @@ end quote labels = overlap_labels(args...) fun = $select - state = KernelState() - grid_dims = blocks isa Integer ? (blocks,) : blocks - for (i, dim) in enumerate(grid_dims) - if dim > MAX_GRID_DIM - error("Grid[$i] exceeds 24-bit limit: max=$MAX_GRID_DIM, got=$dim. " * - "Use multiple kernel launches for larger workloads.") - end - end - # Note: threads=1 lets the driver use the cubin's EIATTR_REQNTID metadata - # which specifies the actual thread count (typically 128 for Tile kernels). - cudacall(fun, Tuple{$(type_exprs...)}, $(arg_exprs...); - blocks=grid_dims, threads, kwargs...) + launch_params(fun, kernel_params(k.f, args...); kwargs...) return nothing end end +# The kernel parameters that the kernel function `f` and the arguments `args` +# flatten to, as a tuple. Its type only depends on the arrays' element types, +# ranks and index types, not on their layouts, so code taking the parameters +# rather than the arguments isn't compiled again for every layout. +# +# `@generated` so that flattening folds to a tuple of field loads; flattening at +# run time costs ~400 ns per launch, even for trivial kernels. +@generated function kernel_params(f, args::Vararg{Any, N}) where {N} + arg_exprs = Any[] + type_exprs = Any[] + # The kernel function comes first: the values it captures are parameters too. + flatten_params!(arg_exprs, type_exprs, f, :f) + for i in 1:N + flatten_params!(arg_exprs, type_exprs, args[i], :(args[$i])) + end + return :(Base.@_inline_meta; ($(arg_exprs...),)) +end + +# Launch `fun` with the parameters `params`, see `kernel_params`. +@noinline function launch_params(fun::CuFunction, params::P; blocks=1, threads=1, + kwargs...) where {P <: Tuple} + grid_dims = blocks isa Integer ? (blocks,) : blocks + for (i, dim) in enumerate(grid_dims) + if dim > MAX_GRID_DIM + error("Grid[$i] exceeds 24-bit limit: max=$MAX_GRID_DIM, got=$dim. " * + "Use multiple kernel launches for larger workloads.") + end + end + # The implicit KernelState comes last, as in codegen. + state = KernelState() + # Note: threads=1 lets the driver use the cubin's EIATTR_REQNTID metadata + # which specifies the actual thread count (typically 128 for Tile kernels). + cudacall(fun, Tuple{P.parameters..., UInt32}, params..., state.seed; + blocks=grid_dims, threads, kwargs...) + return nothing +end + +# A kernel function as CUDACore launches it, taking the parameters of the call +# rather than its arguments (see `compile_and_launch`). +struct ParamsKernel + fun::CuFunction +end +(k::ParamsKernel)(params::Vararg{Any, N}; kwargs...) where {N} = + launch_params(k.fun, params; kwargs...) + #============================================================================= Launch-time overlap detection @@ -1042,11 +1108,14 @@ sharing an element still count as overlapping. end :(memory_range($ex)) end - quote - ranges = ($(ranges...),) - any_overlap(ranges) || return $none - return component_labels(ranges) - end + :(Base.@_inline_meta; range_labels(($(ranges...),))) +end + +# The labels of `ranges`. Out of line, as it only depends on the number of +# arrays, while `overlap_labels` is compiled for every layout of them. +@noinline function range_labels(ranges::NTuple{L, Tuple{Int, Int}}) where {L} + any_overlap(ranges) || return ntuple(_ -> 0, Val(L)) + return component_labels(ranges) end # The groups that `labels` describe for arrays at `leaves`: each group lists the @@ -1102,17 +1171,78 @@ end leaves) = cufunction(k.f, tt; k.opts..., alias_groups=labels_to_groups(labels, leaves)).fun -# `@cuda` compiles from the converted arguments' types, so compile for their -# overlap pattern here rather than for disjoint arrays and then a variant. -function CUDACore.kernel_compile(call::CUDACore.KernelCall{TileBackend}; kwargs...) - tt = Tuple{map(Core.Typeof, call.arguments)...} +# A kernel call 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...) = + compile_converted(values(kwargs), call.f, call.arguments...) + +# The kernel for the converted function `f` and arguments `args`, compiled with +# options `opts`. +function compile_converted(opts::NamedTuple, f::F, args::Vararg{Any, N}) where {F, N} + tt = argument_types(args...) + labels = overlap_labels(args...) # 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=()) + all(iszero, labels) && return lookup_kernel(f, tt, kernel_options(; opts..., alias_groups=())) + return overlapping_kernel(f, tt, labels, opts)::TileKernel{F, tt} +end + +@noinline function overlapping_kernel(f, @nospecialize(tt), labels, opts) + groups = labels_to_groups(labels, array_leaves(tt.parameters)) + return cufunction(f, tt; opts..., alias_groups=groups) +end + +@generated argument_types(args::Vararg{Any, N}) where {N} = + :(Base.@_inline_meta; Tuple{$(args...)}) + + +#============================================================================= + `@cuda backend=cuTile` + + The types of converted arguments are only known at run time: a `TileArray`'s + type records the index type and layout facts of the array it was converted + from. Rather than building CUDACore's `KernelCall` around them, which + constructs its types at run time, `@cuda` converts the kernel function and + its arguments once and passes them to a function specialized on their types, + behind which compiling and launching are static. Kernel calls (`KernelCall`, + `kernel_compile`, `kernel_launch`) take CUDACore's path, converting with the + same adaptor and compiling and launching with the same functions. +=============================================================================# + +function CUDACore.kernel_pipeline(backend::TileBackend, f::F, ::Val{launch}, + args::Vararg{Any, N}; launch_kwargs::NamedTuple=(;), + compiler_kwargs...) where {F, launch, N} + managed = Managed[] + GC.@preserve f args begin + convert_and_launch(backend, managed, Val(launch), launch_kwargs, + values(compiler_kwargs), f, args...) + end +end + +# Converts each argument to a separate value, so that the call below dispatches +# on their types rather than constructing a tuple type at run time. +@generated function convert_and_launch(backend, managed, launch::Val, launch_kwargs, + compiler_kwargs, f, args::Vararg{Any, N}) where {N} + converted = [:(kernel_convert(backend, args[$i], managed)) for i in 1:N] + quote + kernel_f = kernel_convert(backend, f, managed) + compile_and_launch(backend, managed, launch, launch_kwargs, compiler_kwargs, + kernel_f, $(converted...)) + end +end + +@noinline function compile_and_launch(backend, managed, ::Val{launch}, launch_kwargs, + compiler_kwargs, f::F, + args::Vararg{Any, N}) where {launch, F, N} + kernel = compile_converted(compiler_kwargs, f, args...) + if launch + # Acquires the arrays' memory on the launch's stream. Launches the + # parameters, whose types don't depend on the arrays' layouts, so that + # the launch is compiled once for all of them. + CUDACore.managed_kernel_launch(backend, ParamsKernel(kernel.fun), + kernel_params(f, args...), managed; launch_kwargs...) end - return kernel_compile(call.backend, call.f, tt; - kwargs..., alias_groups=alias_groups(call.arguments...)) + return kernel end @@ -1126,7 +1256,7 @@ end num_ctas=nothing, occupancy=nothing, num_worker_warps=nothing, dependent=false, stream=CUDACore.stream(), name=nothing) -Compile and launch a Tile IR kernel. `f` and `args` are converted via +Compile and launch a Tile IR kernel. `f` and `args` are converted as by `cuTileconvert` (CuArray → TileArray, Type → Constant). Equivalent to `@cuda backend=cuTile blocks=grid f(args...)` modulo slight kwarg naming. @@ -1163,12 +1293,10 @@ function launch(@nospecialize(f), grid, args...; dependent::Bool=false, stream=CUDACore.stream(), name::Union{String, Nothing}=nothing) - f = cuTileconvert(f) - converted = map(cuTileconvert, args) - tt = Tuple{map(Core.Typeof, converted)...} - kernel = cufunction(f, tt; sm_arch, opt_level, num_ctas, occupancy, num_worker_warps, name, - alias_groups=alias_groups(converted...)) - kernel(converted...; blocks=grid, dependent, stream) + # As `@cuda` does, so that the launch acquires its arrays' memory on `stream`. + CUDACore.kernel_pipeline(TileBackend(), f, Val(true), args...; + launch_kwargs=(; blocks=grid, dependent, stream), + sm_arch, opt_level, num_ctas, occupancy, num_worker_warps, name) return nothing end diff --git a/src/mapreduce.jl b/src/mapreduce.jl index 6c61d4e6..d2c3929f 100644 --- a/src/mapreduce.jl +++ b/src/mapreduce.jl @@ -65,7 +65,6 @@ end function _mapreducedim!(f, op, R::AbstractArray, A::AbstractArray, reduce_dims::Tuple; init) N = ndims(A) - src_ta = cuTileconvert(A) # Reduced dims first (larger tiles => better hardware reduction) dim_order = (filter(d -> d in reduce_dims, 1:N)..., filter(d -> !(d in reduce_dims), 1:N)...) @@ -75,7 +74,7 @@ function _mapreducedim!(f, op, R::AbstractArray, A::AbstractArray, reduce_dims:: if isempty(reduce_dims) grid = ntuple(d -> cld(size(A, d), ts[d]), N) reduce_stride = ntuple(d -> Int32(1), N) - return _launch_mapreduce!(grid, cuTileconvert(R), src_ta, f, op, ts, reduce_dims, + return _launch_mapreduce!(grid, R, A, f, op, ts, reduce_dims, init, PaddingMode.Zero, reduce_stride, nothing) end @@ -111,27 +110,27 @@ function _mapreducedim!(f, op, R::AbstractArray, A::AbstractArray, reduce_dims:: if atomic_op !== nothing fill!(R, init) - _launch_mapreduce!(grid, cuTileconvert(R), src_ta, f, op, ts, reduce_dims, + _launch_mapreduce!(grid, R, A, f, op, ts, reduce_dims, init, pad_mode, reduce_stride, atomic_op) else # Two-pass: parallelize along par_dim, then reduce partials tmp = similar(A, eltype(R), ntuple(_dim_size, N)) - _launch_mapreduce!(grid, cuTileconvert(tmp), src_ta, f, op, ts, reduce_dims, + _launch_mapreduce!(grid, tmp, A, f, op, ts, reduce_dims, init, pad_mode, reduce_stride, nothing) _mapreducedim!(identity, op, R, tmp, (par_dim,); init) end else grid = ntuple(d -> d in reduce_dims ? 1 : cld(size(A, d), ts[d]), N) reduce_stride = ntuple(d -> Int32(1), N) - _launch_mapreduce!(grid, cuTileconvert(R), src_ta, f, op, ts, reduce_dims, + _launch_mapreduce!(grid, R, A, f, op, ts, reduce_dims, init, pad_mode, reduce_stride, nothing) end end -function _launch_mapreduce!(grid, dest_ta, src_ta, f, op, ts, reduce_dims, +function _launch_mapreduce!(grid, dest, src, f, op, ts, reduce_dims, init, pad_mode, reduce_stride, atomic_op) launch_grid, overflow = _flatten_grid(grid) - launch(mapreduce_kernel, launch_grid, dest_ta, src_ta, + launch(mapreduce_kernel, launch_grid, dest, src, f, op, Constant(ts), Constant(reduce_dims), Constant(overflow), Constant(init), Constant(pad_mode), Constant(reduce_stride), atomic_op === nothing ? Constant(nothing) : atomic_op) diff --git a/src/precompile.jl b/src/precompile.jl index 719365de..e9d15a7d 100644 --- a/src/precompile.jl +++ b/src/precompile.jl @@ -162,6 +162,16 @@ import REPL # without any. precompile(Tuple{typeof(Core.kwcall), NamedTuple{(:alias_groups,), Tuple{Tuple{}}}, typeof(cufunction), typeof(vadd_1d), Type{tt}}) + # `@cuda`, whose generated functions' generators are shared by + # every kernel with as many arguments. + arr = CuArray{T, 1, CUDACore.DeviceMemory} + precompile(Tuple{typeof(Core.kwcall), + NamedTuple{(:launch_kwargs,), Tuple{NamedTuple{(:blocks,), Tuple{Int}}}}, + typeof(CUDACore.kernel_pipeline), TileBackend, typeof(vadd_1d), + Val{true}, arr, arr, arr, Constant{Int, 1024}}) + precompile(compile_and_launch, (TileBackend, Vector{Managed}, Val{true}, + NamedTuple{(:blocks,), Tuple{Int}}, NamedTuple{(), Tuple{}}, + typeof(vadd_1d), tt.parameters...)) end # 2D vec_add: multi-dim block IDs and shapes. @@ -218,5 +228,27 @@ import REPL # Converting the arrays most kernels take. for T in (Float32, Float16), N in 1:4 precompile(cuTileconvert, (CuArray{T, N, CUDACore.DeviceMemory},)) + precompile(kernel_convert, (TileBackend, CuArray{T, N, CUDACore.DeviceMemory}, + Vector{Managed})) + end + + # The generated functions of a broadcast, whose generators every broadcast + # shares. + let arr = CuArray{Float32, 1, CUDACore.DeviceMemory}, + ta = TileArray{Float32, 1, Int32, ArraySpec{1}(128, true)}, + bc = Broadcasted{TiledStyle{1}, Nothing, typeof(+), Tuple{Tiled{arr}, Tiled{arr}}} + precompile(convert_and_broadcast, (Vector{Managed}, Tuple{NTuple{2, Tuple{Bool}}, Tuple{Int}, Tuple{}}, + Tuple{Int}, bc, arr, arr, arr)) + precompile(extrude, (Broadcasted{Nothing, Nothing, typeof(+), Tuple{Tiled{arr}, Tiled{arr}}}, + Tuple{ta, ta}, Val{((true,), (true,))}, KernelAdaptor)) + end + + # Launching the parameters of up to four arrays of rank one or two, which + # every kernel taking them shares (see `compile_and_launch`). + for T in (Float32, Float16), N in 1:2, n in 1:4 + P = Tuple{Iterators.flatten(ntuple(_ -> (Ptr{T}, ntuple(_ -> Int32, 2N)...), n))...} + precompile(Tuple{typeof(Core.kwcall), NamedTuple{(:blocks,), Tuple{Int}}, + typeof(CUDACore.managed_kernel_launch), TileBackend, ParamsKernel, P, + Vector{Managed}}) end end diff --git a/test/device/compilation.jl b/test/device/compilation.jl index b2055605..78cda51b 100644 --- a/test/device/compilation.jl +++ b/test/device/compilation.jl @@ -177,3 +177,107 @@ end kernel(conv(dst), conv(view(src, 2:n+1)); blocks=n÷256) @test Array(dst) == Float32.(2:n+1) end + +@testset "`@cuda` converts arguments with `KernelAdaptor` rules on every launch" begin + # A rule may change values, not only types: each launch must use the values + # its own conversion produced, also when it reuses a compiled kernel. + struct Filler{A} <: Function + dst::A + value::Float32 + end + ct.Adapt.adapt_structure(to, f::Filler) = Filler(ct.Adapt.adapt(to, f.dst), f.value) + ct.Adapt.adapt_structure(to::ct.KernelAdaptor, f::Filler) = + Filler(ct.Adapt.adapt(to, f.dst), 2 * f.value) + (f::Filler)() = (ct.store(f.dst, 1, fill(f.value, (16,))); nothing) + y = CUDA.zeros(Float32, 16) + for gain in (0f0, 3f0, 5f0) + k = @cuda backend=cuTile Filler(y, gain)() + @test Array(y) == fill(2gain, 16) + end + + # and for arguments, including a package's own kernel-side array type + struct Wrapped{T, A<:AbstractVector{T}} <: AbstractVector{T} + parent::A + scale::Float32 + end + Base.size(w::Wrapped) = size(w.parent) + struct WrappedTileArray{T, A<:ct.TileArray{T, 1}} <: ct.AbstractTileArray{T, 1} + parent::A + scale::Float32 + end + ct.Adapt.adapt_structure(to::ct.KernelAdaptor, w::Wrapped) = + WrappedTileArray(ct.Adapt.adapt(to, w.parent), w.scale + 1f0) + function scale_wrapped(dst, w::WrappedTileArray) + ct.store(dst, 1, ct.load(w.parent, 1, (256,)) * w.scale) + return + end + x = CUDA.rand(Float32, 257) + y = CUDA.zeros(Float32, 256) + for (src, scale) in ((view(x, 1:256), 1f0), (view(x, 2:257), 2f0), (view(x, 1:256), 4f0)) + @cuda backend=cuTile scale_wrapped(y, Wrapped(src, scale)) + @test Array(y) ≈ Array(src) .* (scale + 1f0) + end +end + +@testset "`@cuda` records the memory of converted arrays" begin + function copy_tiles(dst, src) + i = ct.bid(1) + ct.store(dst, i, ct.load(src, i, (256,))) + return + end + src = CUDA.rand(Float32, 1025) + dst = CUDA.zeros(Float32, 1024) + call = CUDA.CUDACore.KernelCall(copy_tiles, dst, view(src, 2:1025); + backend=ct.TileBackend()) + @test call.managed == [dst.data[], src.data[]] + @test call.arguments[2].ptr == reinterpret(Ptr{Float32}, pointer(src, 2)) + copy_from(src) = dst -> copy_tiles(dst, src) + call = CUDA.CUDACore.KernelCall(copy_from(src), dst; backend=ct.TileBackend()) + @test call.managed == [src.data[], dst.data[]] +end + +@testset "`@cuda stream=...` orders the launch after other uses of its arrays" begin + function copy_tiles(dst, src) + i = ct.bid(1) + ct.store(dst, i, ct.load(src, i, (256,))) + return + end + function spin_then_fill(a, cycles) + t0 = clock(UInt64) + while clock(UInt64) - t0 < cycles end + i = threadIdx().x + (blockIdx().x - 1) * blockDim().x + i <= length(a) && (a[i] = 1f0) + return + end + function spin(cycles) + t0 = clock(UInt64) + while clock(UInt64) - t0 < cycles end + return + end + cycles = UInt64(200_000_000) + s = CuStream(; flags=CUDA.STREAM_NON_BLOCKING) + # Compiled up front, so that compiling during the test can't outlast the delay. + a = CUDA.zeros(Float32, 256); b = CUDA.zeros(Float32, 256) + @cuda threads=256 spin_then_fill(a, UInt64(0)) + @cuda spin(UInt64(0)) + @cuda backend=cuTile copy_tiles(b, a) + + launches = [(b, a) -> @cuda(backend=cuTile, stream=s, copy_tiles(b, a)), + (b, a) -> ct.launch(copy_tiles, 1, b, a; stream=s)] + for copy! in launches + # written on the task's stream, read on `s` + a = CUDA.zeros(Float32, 256); b = CUDA.zeros(Float32, 256) + device_synchronize() + @cuda threads=256 spin_then_fill(a, cycles) + copy!(b, a) + device_synchronize() + @test all(==(1f0), Array(b)) + + # written on `s` behind other work, read on the task's stream + a = CUDA.ones(Float32, 256); b = CUDA.zeros(Float32, 256) + device_synchronize() + @cuda stream=s spin(cycles) + copy!(b, a) + @test all(==(1f0), Array(b)) + end +end diff --git a/test/host/broadcast.jl b/test/host/broadcast.jl index f5c268fb..e60f8dce 100644 --- a/test/host/broadcast.jl +++ b/test/host/broadcast.jl @@ -1,5 +1,13 @@ using CUDA +# A callable whose kernel-side form differs from its host-side one, to tell +# whether a broadcast converts the functions in its tree. +struct Gain{T} + gain::T +end +(g::Gain)(x) = g.gain * x +ct.Adapt.adapt_structure(::ct.KernelAdaptor, g::Gain) = Gain(2 * g.gain) + @testset "Tiled broadcast" begin @testset "1D element-wise" begin n = 1024 @@ -74,6 +82,30 @@ using CUDA @test Array(C) ≈ Array(A) .+ 2.0f0 end + @testset "functions are converted" begin + n = 1024 + A = CUDA.rand(Float32, n) + C = CUDA.zeros(Float16, n) + ct.@. C = Float16(A) + @test Array(C) == Float16.(Array(A)) + + # also in nested broadcasts, as `Adapt` converts a `Broadcasted` + D = CUDA.zeros(Float32, n) + g = Gain(3f0) + ct.Tiled(D) .= ct.Tiled(A) .+ g.(ct.Tiled(A)) + @test Array(D) ≈ 7 .* Array(A) + end + + @testset "trees with abstract argument types" begin + A = CUDA.rand(Float32, 64) + B = CUDA.rand(Float32, 64) + C = CUDA.zeros(Float32, 64) + bc = Base.Broadcast.Broadcasted{ct.TiledStyle{1}, Nothing, typeof(+), Tuple{Any, Any}}( + +, (A, ct.Tiled(B)), nothing) + Base.Broadcast.materialize!(ct.Tiled(C), bc) + @test Array(C) ≈ Array(A) .+ Array(B) + end + @testset "allocating copy" begin n = 1024 A = CUDA.rand(Float32, n) @@ -246,10 +278,9 @@ using CUDA # which leaves get copied: ranges decide, so a strided view of the # destination's buffer counts even though `Base.mightalias` misses it - copies(dest, args...) = let copies = Any[] - bc = Base.Broadcast.broadcasted(+, args...) - ct.preprocess(bc, ct.cuTileconvert(dest), copies, Val(ndims(dest))) - length(copies) + copies(dest, args...) = let d = ct.cuTileconvert(dest) + leaves = ct.broadcast_leaves(Base.Broadcast.broadcasted(+, args...)) + count(leaf -> ct.needs_copy(d, ct.cuTileconvert(leaf)), leaves) end x, y = CUDA.zeros(Float32, 64), CUDA.zeros(Float32, 64) @test copies(view(x, 2:33), view(x, 1:2:64), 0f0) == 1