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
16 changes: 14 additions & 2 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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*:
Expand Down
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
123 changes: 93 additions & 30 deletions src/broadcast.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
21 changes: 12 additions & 9 deletions src/language/types.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
Loading