diff --git a/NEWS.md b/NEWS.md index 9a6e6455f..bc2176055 100644 --- a/NEWS.md +++ b/NEWS.md @@ -26,9 +26,23 @@ releases](https://github.com/JuliaGPU/cuTile.jl/releases). command that assembles it, its disassembly, the CUBIN, PTX and SASS. The bytecode serves as a reproducer for `tileiras` problems; `debuginfo=false` leaves source locations, which include absolute file paths, out of it. +- `ct.autotune(f, space)` selects the fastest configuration of a launch, such as + its tile sizes and compiler hints, from a search space: it compiles the + configurations concurrently, then times those that compiled. +- `ct.@tuned(space...) do cfg … end` launches with the configuration a tuning + record names, or else the first one; with `search=true` a launch without a + record searches the space first and saves the winner. Records are found by + the code the launch compiles to, are kept per package, and can be shipped + with a package. +- The matmul, batched matmul, fused GEMM, FMHA, MoE and layer-norm examples + choose their tile sizes and hints with `ct.@tuned`, and ship tuning records + for the RTX 5080; `examples/benchmarks.jl --search` tunes the launches that + have no applicable record. *Minor changes*: +- cuTile.jl requires CUDA.jl 6.6, whose `@cuda` accepts splatted keyword + arguments, such as a configuration's compiler hints. - `CUDA_Tile_jll` is no longer a dependency. `code_tiled` and `@device_code_tiled` disassemble with the `tileirdisasm` that ships with CUDA 13.4 and newer, which `CUDA_Compiler_jll` selects by default on any CUDA 13 diff --git a/Project.toml b/Project.toml index 4aed187c4..c947e500f 100644 --- a/Project.toml +++ b/Project.toml @@ -22,6 +22,8 @@ PrecompileTools = "aea7be01-6a6a-4083-8856-8a6e6704d82a" Preferences = "21216c6a-2e73-6563-6e65-726566657250" REPL = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" +Scratch = "6c6a2e73-6563-6170-7368-637461726353" +TOML = "fa267f1f-6049-4f14-aa54-33bafae1ed76" [weakdeps] DLFP8Types = "f4c16678-4a16-415b-82ef-ed337c5d6c7c" @@ -34,7 +36,7 @@ MicrofloatsExt = "Microfloats" [compat] Adapt = "4.4" BFloat16s = "0.6" -CUDACore = "6.3" +CUDACore = "6.6" CUDA_Compiler_jll = "0.6.3" CompilerCaching = "0.6.1" DLFP8Types = "0.1.0" @@ -49,4 +51,6 @@ PrecompileTools = "1" Preferences = "1.5" REPL = "1" Random = "1.11" +Scratch = "1.2" +TOML = "1" julia = "1.11" diff --git a/README.md b/README.md index 13cebbb7e..1d7e65792 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,9 @@ julia --project=examples examples/benchmarks.jl # Julia uv run python examples/benchmarks.py # Python (for comparison) ``` +The Julia examples use the tuning records they ship (made on an RTX 5080) where these +apply; pass `--search` to tune the launches that have no applicable record first. + Results comparing cuTile.jl against cuTile Python on an RTX 5080 (`tileiras` 13.2.51, 20 runs, 5 warmup, min time reported): diff --git a/docs/src/lib/host.md b/docs/src/lib/host.md index 1eafbf4a5..01fe99702 100644 --- a/docs/src/lib/host.md +++ b/docs/src/lib/host.md @@ -8,3 +8,15 @@ CurrentModule = cuTile Tiled @__dot__ ``` + + +## Autotuning + +```@docs +autotune +TuningResult +@tuned +tuned +tuning_store +clear_tuning! +``` diff --git a/docs/src/man/performance.md b/docs/src/man/performance.md index 34130536e..2282be193 100644 --- a/docs/src/man/performance.md +++ b/docs/src/man/performance.md @@ -4,20 +4,72 @@ This chapter describes advanced performance tuning for cuTile kernels. ## Choosing tile sizes -cuTile.jl has no autotuner. Tile sizes are ordinary -[`ct.Constant`](execution.md#Compile-time-arguments) arguments, so tuning them is a -loop on the host, with every configuration compiling its own kernel: +Tile sizes are ordinary [`ct.Constant`](execution.md#Compile-time-arguments) arguments +and hints are launch keywords, so the best values for a kernel can be found by trying +them. [`ct.autotune`](@ref cuTile.autotune) does that. It takes a function that +performs the launch for one configuration, and a search space, here every combination +of the values given for each field: ```julia -for (tm, tn, tk) in ((64, 128, 64), (128, 128, 32), (128, 128, 64)) - launch() = @cuda backend=cuTile blocks=cld(M, tm) * cld(N, tn) matmul( +space = (tm=(128, 64, 256), tn=(128, 64, 256), tk=(32, 16, 64), occupancy=(2, 1, 4)) +result = ct.autotune(space) do (; tm, tn, tk, occupancy) + @cuda backend=cuTile blocks=cld(M, tm) * cld(N, tn) occupancy=occupancy matmul( A, B, C, ct.Constant(tm), ct.Constant(tn), ct.Constant(tk)) - launch() # compile - t = minimum(CUDA.@elapsed(launch()) for _ in 1:20) - println((tm, tn, tk), ": ", round(t * 1000; digits=3), " ms") end ``` +`result.best` is the selected configuration, and displaying `result` ranks all of them: + +``` +TuningResult: best of 81 configurations is (tm = 64, tn = 128, tk = 32, occupancy = 2) +compiled in 4.0 s, timed in 3.5 s + time (ms) samples configuration + 2.422 1.0× 10 tm = 64, tn = 128, tk = 32, occupancy = 2 ← best + 2.449 1.01× 10 tm = 128, tn = 64, tk = 32, occupancy = 2 + 2.457 1.01× 10 tm = 128, tn = 64, tk = 16, occupancy = 4 + ⋮ + 81.12 33.5× 1 tm = 256, tn = 256, tk = 16, occupancy = 4 +``` + +This is the kernel of the `Float32` matmul example at 4096³ on an RTX 5080, with the +kernels already in the disk cache; compiling all 81 from scratch took 10–20 s. The +first configuration of the space, the example's hand-picked default, came 10th at +1.03×. + +A field can also hold several compiler hints at once, as a `NamedTuple` that is splatted +into `@cuda`. An empty one leaves the kernel's own `@compiler_options` in effect: + +```julia +space = (tm=(128, 64), tn=(128, 64), + hints=((;), (occupancy=2,), (occupancy=2, num_worker_warps=8))) +result = ct.autotune(space) do (; tm, tn, hints) + @cuda backend=cuTile blocks=cld(M, tm) * cld(N, tn) hints... matmul( + A, B, C, ct.Constant(tm), ct.Constant(tn), ct.Constant(32)) +end +``` + +The search compiles every configuration first, concurrently, and then times them in +turns, dropping the configurations that fall far behind. Configurations within 2% of +the fastest count as equally fast, and the earliest of them in the space wins, so put +the configuration you would use without tuning first. A configuration that fails to +compile is reported in the table and skipped. The compiled kernels are the ones a +later launch with the same arguments uses, so launching the winner needs no +compilation, and the compiled code is cached on disk (see +[Caching](execution.md#Caching)), so that searching again in a later session mostly +skips `tileiras`. + +The search launches every configuration many times on the same arrays. A kernel that +reads what it writes, such as one that accumulates into its output, needs its inputs +restored before each launch: pass a `setup` function, which is called with the +configuration before every launch, or tune on scratch data whose contents do not +matter. `ct.autotune` does not remember its result: use `result.best` to choose the +values in your code, or let the launch site look them up, as described next. + +The search times each launch as the host sees it, including the launch overhead of +several microseconds. When that overhead sets the pace, as for a kernel that takes only +a few microseconds, configurations whose kernels differ in speed can measure the same, +and the earliest of them wins. + The following starting points were measured on an RTX 5080 (sm_120) with `tileiras` 13.5, using the examples, without locked clocks. @@ -85,6 +137,119 @@ It only covers compiler hints. Tile sizes are chosen on the host, so choosing th architecture takes a check of `CUDA.capability(CUDA.device())`. +## Tuned launches + +[`ct.@tuned`](@ref cuTile.@tuned) makes a launch use the configuration that tuning +found, on whatever GPU, element type and array layout it runs with. The call site lists +the candidates as `autotune` takes them, and `ct.@tuned` calls the function with the +chosen one: + +```julia +function matmul!(C, A, B; search::Bool=false) + M, N = size(C) + ct.@tuned(search=search, tm=(128, 64, 256), tn=(128, 64, 256), occupancy=(2, 1, 4)) do (; tm, tn, occupancy) + @cuda backend=cuTile blocks=cld(M, tm) * cld(N, tn) occupancy=occupancy matmul( + A, B, C, ct.Constant(tm), ct.Constant(tn), ct.Constant(32)) + end +end +``` + +Without a tuning record for this launch, the first configuration is used, so list the +values you would pick by hand first. `matmul!(C, A, B; search=true)` instead searches the +space with `ct.autotune` the first time, saves the winner as a record, and launches it; +every later call, in this session or another, uses the record, whether or not it passes +`search=true`. A search takes seconds (the 81 configurations of the `ct.autotune` +example above took about 8 s with their kernels in the disk cache, and 10–20 s without), +so searching is off by default and is for the code that calls `matmul!` to ask for. A +library can offer one switch for all its tuned launches by defaulting the keyword to a +setting of its own, as cuDNN.jl's `autotune` keyword does. + +The space can also be given positionally, as a collection of `NamedTuple`s, which is how +to leave out combinations: `ct.@tuned(((; tm, tn) for tm in (128, 64), tn in (128, 64) if +tm >= tn); search) do (; tm, tn) … end`. + +### Which record applies + +Records are found by what the launch compiles to, not by a name. Before choosing, +`ct.@tuned` calls the function once with the first configuration while launches only +compile, as `autotune` does, and looks up the record for the code of the kernels this +launches, the search space and the GPU's compute capability. A record therefore applies +again after a restart or in another installation, and stops applying when the code that +the first configuration compiles to changes: when the kernel or anything it calls is +edited, or when it is launched on another element type or array layout (a view instead +of a whole array, for instance). Another search makes a new record; nothing needs to be +declared or invalidated by hand. Changes that only affect other configurations, such as +code reached only with larger tiles, are not noticed. + +Values that change which configuration is fastest without changing the kernel's code +are not seen, the size of the problem in particular. Pass them as `key`, rounded so that +similar values share a record: `ct.@tuned(key=(nextpow(2, M), nextpow(2, N)), …)`. + +The choice is remembered for the rest of the session per call site: the type of the +function passed to `ct.@tuned`, which includes the types of the variables it uses, +`key`, the space and the GPU. Calls that differ in a value the types do not show, such +as a head dimension passed as a `ct.Constant`, therefore launch the configuration chosen +for the first of them, until a method is defined anywhere, which makes every call site +look again. Put such values in `key` as well. + +### What the launch function may do + +The function passed to `ct.@tuned` is called more than once: to identify the launch, and +many times during a search. It must only compute on the host and launch cuTile kernels +on the task's stream, and which kernels it launches must not depend on the results of +earlier launches in the same call. Other GPU work in it, such as a `copyto!` or a +CUDA.jl kernel, runs on every call, also while identifying the launch. A function that +launches no cuTile kernel is rejected. + +A search launches the kernels many times on the arrays the call was given. For a kernel +that reads what it writes, pass `setup`, which the call that searches calls with the +configuration before every launch of the search and once more before the launch that +counts, to restore the inputs (see `ct.autotune`). Searching while capturing a CUDA graph throws an error. When +several tasks reach a launch that has no record at the same time, one of them searches +and the others wait for it, then launch with the result. + +### Where records are kept + +Each record is a small TOML file holding the chosen configuration, the times of all +configurations, and the GPU, cuTile and `tileiras` versions it was made with. Calls in a +package keep them in a scratch space of that package, which +[`ct.tuning_store`](@ref cuTile.tuning_store)`(MyLib)` returns and which is removed +with the package; calls outside a package, as in a script or the REPL, use the scratch +space `Scratch.@get_scratch!` uses there (the active project's if it is a package, and +otherwise a global one). Pass `store=dir` to keep them in a directory of your choice. When the +store cannot be written to, the record is kept in memory for the session and a warning +is shown. [`ct.clear_tuning!`](@ref cuTile.clear_tuning!)`(MyLib)` deletes the records of +a package and makes this session forget its choices, so that the next call with +`search=true` searches again, unless a shipped record applies. Deleting one of the files +does the same for one record from the next session, or the next method definition, on. + +A package can ship records for the GPUs it was tuned on: tune, copy the files from its +store into a directory of the repository, and pass that directory as `shipped`: + +```julia +ct.@tuned(shipped=joinpath(pkgdir(MyLib), "tuning"), search=search, tm=…) do cfg … end +``` + +A shipped record applies wherever cuTile generates the same code for the launch, in +practice with the same cuTile minor version, on a GPU of the same compute capability. +Records made on a GPU with the same name come first, then those from other GPUs; within +each, the store comes before the shipped records, so that a user's own search takes +precedence. As the search space is part of what identifies a record, changing it, even +only the order of its values, also takes new records. + +The examples in the repository work this way. Their launches are tuned, with records for +an RTX 5080 in `examples/tuning`, and their `run` functions take `search=true`, which +the benchmark runner passes when asked: + +```bash +julia --project=examples examples/benchmarks.jl --search matmul fmha +``` + +This searches the launches that have no applicable record, as on a GPU of another +compute capability, keeps the new records in the global scratch space (see +`ct.tuning_store(Main)`), and reports the times with them. + + ## Kernel configuration `ct.@compiler_options` sets optimization hints inside a kernel function body: diff --git a/docs/src/tutorials/matmul.md b/docs/src/tutorials/matmul.md index 8210ada04..2212fdc7d 100644 --- a/docs/src/tutorials/matmul.md +++ b/docs/src/tutorials/matmul.md @@ -275,8 +275,9 @@ computes: occupancy, which matter a lot for GEMM. See [Performance](../man/performance.md). -`examples/matmul.jl` in the repository is this kernel plus both of those, and -`examples/batchmatmul.jl` extends it to batched operands using trailing batch +`examples/matmul.jl` in the repository is this kernel plus both of those, with +its tile sizes and hints chosen by [`ct.@tuned`](../man/performance.md#Tuned-launches), +and `examples/batchmatmul.jl` extends it to batched operands using trailing batch dimensions on `muladd`. For block-scaled FP8 and FP4 matmuls, see [`ct.muladd_scaled`](../lib/operations.md#Matrix-multiplication) and `examples/blockscaled_matmul.jl`. diff --git a/examples/Project.toml b/examples/Project.toml index c6e4b50db..409807ecc 100644 --- a/examples/Project.toml +++ b/examples/Project.toml @@ -10,7 +10,7 @@ cuTile = "0dea8319-8c4a-4662-a73d-20234d115b9a" cuTile = {path = ".."} [compat] -CUDA = "6.5" +CUDA = "6.6" FFTW = "1.10.0" Microfloats = "0.2.6" NVTX = "1.0.3" diff --git a/examples/batchmatmul.jl b/examples/batchmatmul.jl index c613354f7..c4a90b9a8 100644 --- a/examples/batchmatmul.jl +++ b/examples/batchmatmul.jl @@ -14,7 +14,7 @@ import cuTile as ct # Grid: (M_tiles, N_tiles, Batch) function batch_matmul_kernel(A::ct.TileArray{T,3}, B::ct.TileArray{T,3}, C::ct.TileArray{T,3}, tm::Int, tn::Int, tk::Int) where {T} - # On sm_120, targeting two CTAs per SM is faster with the default tile sizes in `run` + # On sm_120, targeting two CTAs per SM is faster with the default tile sizes of `batch_matmul!` ct.@compiler_options occupancy=ct.ByTarget(v"12.0" => 2) # Grid dimensions (1-indexed) @@ -58,6 +58,35 @@ function batch_matmul_kernel(A::ct.TileArray{T,3}, B::ct.TileArray{T,3}, C::ct.T return nothing end +#============================================================================= + Host-side wrapper +=============================================================================# + +# C[:, :, b] = A[:, :, b] * B[:, :, b] with the given tile sizes. `hints` are compiler +# hints for the launch, overriding the kernel's `@compiler_options`. +function batch_matmul!(C, A, B, tm, tn, tk; hints...) + M, N, Batch = size(C) + @cuda backend=cuTile blocks=(cld(M, tm), cld(N, tn), Batch) hints... batch_matmul_kernel( + A, B, C, ct.Constant(tm), ct.Constant(tn), ct.Constant(tk)) + return C +end + +# The same with the tile sizes and hints that tuning found for this GPU, or else the +# first of each: 128x128 output tiles that span 128 bytes along K (see matmul.jl), and the +# kernel's own hints. With `search=true`, a launch without a tuning record first tries +# every combination and records the fastest. +function batch_matmul!(C, A, B; search::Bool=false) + M, N, Batch = size(C) + K = size(A, 2) + tk = eltype(A) === Float32 ? (32, 16, 64) : (64, 32, 16) + ct.@tuned(search=search, shipped=joinpath(@__DIR__, "tuning"), + key=nextpow.(2, (M, N, K, Batch)), + tm=(128, 64, 256), tn=(128, 64, 256), tk=tk, + hints=((;), (occupancy=1,), (occupancy=2,), (occupancy=4,))) do (; tm, tn, tk, hints) + batch_matmul!(C, A, B, tm, tn, tk; hints...) + end +end + #============================================================================= Example harness =============================================================================# @@ -76,21 +105,20 @@ function prepare(; benchmark::Bool=false, ) end -# `tk` makes tiles span 128 bytes along K (see matmul.jl) -function run(data; tm::Int=128, tn::Int=128, tk::Int=eltype(data.A) === Float32 ? 32 : 64, - nruns::Int=1, warmup::Int=0) - (; A, B, C, M, N, Batch) = data - grid = (cld(M, tm), cld(N, tn), Batch) +function run(data; search::Bool=false, nruns::Int=1, warmup::Int=0) + (; A, B, C) = data + # the first call compiles, and searches if asked to + batch_matmul!(C, A, B; search) CUDA.@sync for _ in 1:warmup - @cuda backend=cuTile blocks=grid batch_matmul_kernel(A, B, C, ct.Constant(tm), ct.Constant(tn), ct.Constant(tk)) + batch_matmul!(C, A, B; search) end times = Float64[] NVTX.@range "cuTile" begin for i in 1:nruns NVTX.@range "run $i" begin - t = CUDA.@elapsed @cuda backend=cuTile blocks=grid batch_matmul_kernel(A, B, C, ct.Constant(tm), ct.Constant(tn), ct.Constant(tk)) + t = CUDA.@elapsed batch_matmul!(C, A, B; search) push!(times, t * 1000) # ms end end @@ -154,11 +182,16 @@ end Main =============================================================================# -function test_batch_matmul(::Type{T}, M, K, N, Batch, tm, tn, tk; name=nothing) where T - name = something(name, "batch_matmul ($M x $K x $Batch) @ ($K x $N x $Batch), $T, tiles=$tm x $tn x $tk") +function test_batch_matmul(::Type{T}, M, K, N, Batch, tiles=nothing; name=nothing) where T + name = something(name, "batch_matmul ($M x $K x $Batch) @ ($K x $N x $Batch), $T, " * + (tiles === nothing ? "tuned tiles" : "tiles=$(join(tiles, " x "))")) println("--- $name ---") data = prepare(; M, K, N, Batch, T) - result = run(data; tm, tn, tk) + result = if tiles === nothing + run(data) + else + (; C=batch_matmul!(data.C, data.A, data.B, tiles...)) + end verify(data, result) println(" passed") end @@ -166,9 +199,10 @@ end function main() println("--- cuTile Batch Matrix Multiplication Examples ---\n") - test_batch_matmul(Float32, 256, 128, 256, 4, 32, 32, 32) - test_batch_matmul(Float32, 512, 256, 512, 4, 64, 64, 64) - test_batch_matmul(Float16, 512, 256, 1024, 4, 128, 256, 64) + test_batch_matmul(Float32, 256, 128, 256, 4) + test_batch_matmul(Float32, 256, 128, 256, 4, (32, 32, 32)) + test_batch_matmul(Float32, 512, 256, 512, 4, (64, 64, 64)) + test_batch_matmul(Float16, 512, 256, 1024, 4, (128, 256, 64)) println("\n--- All batch matmul examples completed ---") end diff --git a/examples/benchmarks.jl b/examples/benchmarks.jl index 66eb043ab..7ed38f837 100644 --- a/examples/benchmarks.jl +++ b/examples/benchmarks.jl @@ -12,6 +12,10 @@ using CUDA const NRUNS = 20 const WARMUP = 5 +# With `--search`, examples whose launches are tuned (see their `run`) search for the +# fastest configuration where they have no tuning record, and record it. +const SEARCH = "--search" in ARGS + #============================================================================= Benchmark Utilities =============================================================================# @@ -102,7 +106,9 @@ function run_benchmark(name::String) end # Run cuTile - result = @invokelatest mod.run(data; nruns=NRUNS, warmup=WARMUP) + tuned = @invokelatest hasmethod(mod.run, Tuple{Any}, (:search,)) + kwargs = SEARCH && tuned ? (; search=true) : (;) + result = @invokelatest mod.run(data; nruns=NRUNS, warmup=WARMUP, kwargs...) # Extract times from result if hasproperty(result, :times) @@ -142,6 +148,7 @@ function main(args...) println("Configuration:") println(" Runs: $NRUNS (+ $WARMUP warmup)") println(" GPU: ", CUDA.name(CUDA.device())) + println(" Searching for tuned configurations: ", SEARCH ? "yes" : "no") for name in discover_benchmarks(args...) println("\nBenchmarking $name...") @@ -185,5 +192,5 @@ function main(args...) end if abspath(PROGRAM_FILE) == @__FILE__ - main(ARGS...) + main(filter(!=("--search"), ARGS)...) end diff --git a/examples/fmha.jl b/examples/fmha.jl index db91a3387..a83a95ceb 100644 --- a/examples/fmha.jl +++ b/examples/fmha.jl @@ -143,19 +143,36 @@ end Host-side wrapper =============================================================================# +# Out = attention(Q, K, V) with the given tile sizes. `hints` are compiler hints for the +# launch, overriding the kernel's `@compiler_options`. +function fmha!(Out, Q, K, V, qk_scale, input_pos, query_group_size, causal, tile_m, tile_n; + hints...) + D_k, SeqLen_Q, Heads, Batch = size(Q) + SeqLen_KV = size(K, 2) + even_k = (SeqLen_KV % tile_n) == 0 + grid = (cld(SeqLen_Q, tile_m), Batch * Heads) + @cuda backend=cuTile blocks=grid hints... fmha_kernel( + Q, K, V, Out, qk_scale, Int32(input_pos), ct.Constant(D_k), ct.Constant(Heads), + ct.Constant(tile_m), ct.Constant(tile_n), ct.Constant(query_group_size), + ct.Constant(causal), ct.Constant(even_k)) + return Out +end + # On sm_120, 128x128 tiles spill registers at occupancy 2 and run at less than half # the speed of 64x64 tiles, which TileGym uses on sm_120 and sm_121. default_tiles() = capability(device()).major == 12 ? (64, 64) : (128, 128) +# Uses the tile sizes and hints that tuning found for this GPU, or else the first of +# each: `default_tiles()` and the kernel's own hints. With `search=true`, a launch +# without a tuning record first tries every combination and records the fastest. function cutile_fmha(Q::CuArray{T}, K::CuArray{T}, V::CuArray{T}; qk_scale::Union{Float32,Nothing}=nothing, input_pos::Int=0, - tile_m::Int=default_tiles()[1], tile_n::Int=default_tiles()[2], query_group_size::Int=1, - causal::Bool=false) where {T} + causal::Bool=false, + search::Bool=false) where {T} D_k, SeqLen_Q, Heads, Batch = size(Q) D_v, SeqLen_KV, KV_Heads, _ = size(V) - even_k = (SeqLen_KV % tile_n) == 0 if qk_scale === nothing qk_scale = Float32(1.0 / sqrt(D_k)) @@ -163,12 +180,19 @@ function cutile_fmha(Q::CuArray{T}, K::CuArray{T}, V::CuArray{T}; Out = CuArray{T}(undef, D_v, SeqLen_Q, Heads, Batch) - grid_x = cld(SeqLen_Q, tile_m) - grid_y = Batch * Heads - - @cuda backend=cuTile blocks=(grid_x, grid_y) fmha_kernel(Q, K, V, Out, qk_scale, Int32(input_pos), ct.Constant(D_k), ct.Constant(Heads), ct.Constant(tile_m), ct.Constant(tile_n), ct.Constant(query_group_size), ct.Constant(causal), ct.Constant(even_k)) - - return Out + tm, tn = default_tiles() + # Tuning choices are remembered per call site for the session, so values that differ + # between calls and that the kernel takes as constants go in `key`, as does the + # problem size. That includes SeqLen_KV exactly, as whether the tiles divide it + # decides `even_k`. + ct.@tuned(search=search, shipped=joinpath(@__DIR__, "tuning"), + key=(D_k, Heads, query_group_size, causal, nextpow(2, SeqLen_Q), SeqLen_KV, + nextpow(2, Batch)), + tile_m=unique((tm, 64, 128)), tile_n=unique((tn, 64, 128)), + hints=((;), (occupancy=1,), (occupancy=4,))) do (; tile_m, tile_n, hints) + fmha!(Out, Q, K, V, qk_scale, input_pos, query_group_size, causal, tile_m, tile_n; + hints...) + end end @@ -236,7 +260,6 @@ function prepare(; benchmark::Bool=false, d_k::Int = 64, d_v::Int = 64, query_group_size::Int = 1, causal::Bool = true, - tile_m::Int = default_tiles()[1], tile_n::Int = default_tiles()[2], T::DataType = Float16) kv_heads = heads ÷ query_group_size @@ -248,26 +271,26 @@ function prepare(; benchmark::Bool=false, return (; Q, K, V, batch, heads, seq_q, seq_kv, d_k, d_v, - query_group_size, causal, - tile_m, tile_n + query_group_size, causal ) end -function run(data; nruns::Int=1, warmup::Int=0) - (; Q, K, V, causal, tile_m, tile_n, query_group_size) = data +function run(data; search::Bool=false, nruns::Int=1, warmup::Int=0) + (; Q, K, V, causal, query_group_size) = data + # the first call compiles, and searches if asked to + out = cutile_fmha(Q, K, V; query_group_size, causal, search) CUDA.@sync for _ in 1:warmup - cutile_fmha(Q, K, V; tile_m, tile_n, query_group_size, causal) + cutile_fmha(Q, K, V; query_group_size, causal, search) end times = Float64[] - out = nothing NVTX.@range "cuTile" begin for i in 1:nruns NVTX.@range "run $i" begin t = CUDA.@elapsed begin - out = cutile_fmha(Q, K, V; tile_m, tile_n, query_group_size, causal) + out = cutile_fmha(Q, K, V; query_group_size, causal, search) end push!(times, t * 1000) # ms end @@ -304,13 +327,12 @@ end =============================================================================# function test_fmha(batch, heads, seq_q, seq_kv, d_k, d_v; - causal=false, tile_m=default_tiles()[1], tile_n=default_tiles()[2], - query_group_size=1, T=Float16, name=nothing) + causal=false, query_group_size=1, T=Float16, name=nothing) name = something(name, "fmha B=$batch H=$heads M=$seq_q N=$seq_kv " * "D=$d_k causal=$causal $T") println("--- $name ---") data = prepare(; batch, heads, seq_q, seq_kv, d_k, d_v, - query_group_size, causal, tile_m, tile_n, T) + query_group_size, causal, T) result = run(data) verify(data, result) println(" passed") diff --git a/examples/fused_gemm.jl b/examples/fused_gemm.jl index ca2ba39bc..267308039 100644 --- a/examples/fused_gemm.jl +++ b/examples/fused_gemm.jl @@ -36,6 +36,35 @@ function fused_gemm_kernel(C::ct.TileArray{T}, A, B, bias, act, return end +#============================================================================= + Host-side wrapper +=============================================================================# + +# C = act.(A * B .+ bias') with the given tile sizes and `occupancy` compiler hint (see +# the Performance chapter of the manual). +function fused_gemm!(C, A, B, bias, act, tm, tn, tk; occupancy::Int=2) + M, N = size(C) + # Unlike matmul.jl, no block swizzle: on an RTX 5080 it gains under 2% here. + @cuda backend=cuTile blocks=(cld(M, tm), cld(N, tn)) occupancy=occupancy fused_gemm_kernel( + C, A, B, bias, act, ct.Constant(tm), ct.Constant(tn), ct.Constant(tk)) + return C +end + +# The same with the tile sizes and occupancy that tuning found for this GPU, or else +# the first of each. Two CTAs per SM is about 12% faster than the compiler's default on +# an RTX 5080 (sm_120) at the benchmark shape. With `search=true`, a launch without a +# tuning record first tries every combination and records the fastest. +function fused_gemm!(C, A, B, bias, act; search::Bool=false) + M, N = size(C) + K = size(A, 2) + ct.@tuned(search=search, shipped=joinpath(@__DIR__, "tuning"), + key=nextpow.(2, (M, N, K)), + tm=(128, 64, 256), tn=(128, 64, 256), tk=(64, 32, 16), + occupancy=(2, 1, 4)) do (; tm, tn, tk, occupancy) + fused_gemm!(C, A, B, bias, act, tm, tn, tk; occupancy) + end +end + #============================================================================= Example harness =============================================================================# @@ -59,27 +88,20 @@ function prepare(; benchmark::Bool=false, ) end -# `occupancy` is a compiler hint (see the Performance chapter of the manual). -# Two CTAs per SM is about 12% faster than the default on an RTX 5080 (sm_120) -# at the benchmark shape. -function run(data; tm::Int=128, tn::Int=128, tk::Int=64, occupancy::Int=2, - nruns::Int=1, warmup::Int=0) - (; A, B, bias, C, act, M, N) = data - # Unlike matmul.jl, no block swizzle: on an RTX 5080 it gains under 2% here. - grid = (cld(M, tm), cld(N, tn)) - launch() = @cuda backend=cuTile blocks=grid occupancy=occupancy fused_gemm_kernel( - C, A, B, bias, act, ct.Constant(tm), ct.Constant(tn), ct.Constant(tk)) +function run(data; search::Bool=false, nruns::Int=1, warmup::Int=0) + (; A, B, bias, C, act) = data - launch() + # the first call compiles, and searches if asked to + fused_gemm!(C, A, B, bias, act; search) CUDA.@sync for _ in 1:warmup - launch() + fused_gemm!(C, A, B, bias, act; search) end times = Float64[] NVTX.@range "cuTile" begin for i in 1:nruns NVTX.@range "run $i" begin - t = CUDA.@elapsed launch() + t = CUDA.@elapsed fused_gemm!(C, A, B, bias, act; search) push!(times, t * 1000) # ms end end @@ -139,11 +161,16 @@ end Main =============================================================================# -function test_fused_gemm(M, N, K, tm, tn, tk; T=Float16, S=T, act=gelu, name=nothing) - name = something(name, "act.(A * B .+ bias'), ($M x $K) @ ($K x $N), $S → $T, act=$act, tiles=$tm x $tn x $tk") +function test_fused_gemm(M, N, K, tiles=nothing; T=Float16, S=T, act=gelu, name=nothing) + name = something(name, "act.(A * B .+ bias'), ($M x $K) @ ($K x $N), $S → $T, act=$act, " * + (tiles === nothing ? "tuned tiles" : "tiles=$(join(tiles, " x "))")) println("--- $name ---") data = prepare(; M, N, K, T, S, act) - result = run(data; tm, tn, tk) + result = if tiles === nothing + run(data) + else + (; C=fused_gemm!(data.C, data.A, data.B, data.bias, data.act, tiles...)) + end verify(data, result) println(" passed") end @@ -151,11 +178,12 @@ end function main() println("--- cuTile Fused GEMM Examples ---\n") - test_fused_gemm(256, 256, 256, 64, 64, 64) - test_fused_gemm(256, 256, 256, 64, 64, 64; act=silu) - test_fused_gemm(300, 200, 100, 64, 64, 32; act=x -> max(x, zero(x)), name="ReLU as a closure, ragged sizes") - test_fused_gemm(512, 256, 384, 128, 128, 64; S=ct.BFloat16, T=ct.BFloat16) - test_fused_gemm(256, 512, 256, 64, 128, 64; T=Float32, S=Float16, act=tanh) + test_fused_gemm(256, 256, 256) + test_fused_gemm(256, 256, 256, (64, 64, 64)) + test_fused_gemm(256, 256, 256, (64, 64, 64); act=silu) + test_fused_gemm(300, 200, 100, (64, 64, 32); act=x -> max(x, zero(x)), name="ReLU as a closure, ragged sizes") + test_fused_gemm(512, 256, 384, (128, 128, 64); S=ct.BFloat16, T=ct.BFloat16) + test_fused_gemm(256, 512, 256, (64, 128, 64); T=Float32, S=Float16, act=tanh) println("\n--- All fused GEMM examples completed ---") end diff --git a/examples/layernorm.jl b/examples/layernorm.jl index a770fbb7e..0067cdf79 100644 --- a/examples/layernorm.jl +++ b/examples/layernorm.jl @@ -233,27 +233,54 @@ function prepare(; benchmark::Bool=false, ) end -# The backward kernel takes a lock once per tile along N, so it is fastest with one tile -# per row, up to 4096 elements; wider tiles were slower again on an RTX 5080. The final -# dW/dB reduction launches one block per tile along N, so it gets narrower tiles. -function run(data; TILE_N::Int=min(nextpow(2, data.N), 4096), TILE_M::Int=32, - TILE_N_DWDB::Int=128, nruns::Int=1, warmup::Int=0) +# Both main kernels loop over a row of N elements, and the backward one takes a lock once +# per tile, so by default a tile spans the row, up to 4096 elements; wider tiles were +# slower again on an RTX 5080. Tuning can pick another width and compiler hints. The +# final dW/dB reduction launches one block per tile along N, so it gets narrow tiles; it +# takes about 10 µs, too little for tuning to time reliably, so its tiles are fixed. +# +# Tuning choices are remembered per call site for the session, so `key` holds the values +# that the kernels take as constants, besides the problem size. +function run(data; search::Bool=false, nruns::Int=1, warmup::Int=0) (; X, W, B, Y, Mean, Rstd, DY, DX, DW_partial, DB_partial, Locks, FINAL_DW, FINAL_DB, M, N, eps, GROUP_SIZE_M) = data + tile_ns = unique((min(nextpow(2, N), 4096), 1024, 2048, 4096)) + hint_sets = ((;), (occupancy=1,), (occupancy=2,), (occupancy=4,)) + TILE_M, TILE_N_DWDB = 32, 128 function run_fwd() - @cuda backend=cuTile blocks=M layer_norm_fwd(X, W, B, Y, Mean, Rstd, ct.Constant(eps), ct.Constant(TILE_N)) + ct.@tuned(search=search, shipped=joinpath(@__DIR__, "tuning"), + key=(eps, nextpow.(2, (M, N))...), + tile_n=tile_ns, hints=hint_sets) do (; tile_n, hints) + @cuda backend=cuTile blocks=M hints... layer_norm_fwd( + X, W, B, Y, Mean, Rstd, ct.Constant(eps), ct.Constant(tile_n)) + end end - function run_bwd() + function reset_partials!() fill!(DW_partial, 0) fill!(DB_partial, 0) fill!(Locks, 0) - @cuda backend=cuTile blocks=M layer_norm_bwd_dx_partial_dwdb(DX, DY, DW_partial, DB_partial, X, W, Mean, Rstd, Locks, ct.Constant(GROUP_SIZE_M), ct.Constant(TILE_N)) - num_tiles_n = cld(N, TILE_N_DWDB) - @cuda backend=cuTile blocks=num_tiles_n layer_norm_bwd_dwdb(DW_partial, DB_partial, FINAL_DW, FINAL_DB, ct.Constant(TILE_M), ct.Constant(TILE_N_DWDB)) end + function run_bwd() + # The kernel accumulates into the partial gradients: reset them here for the + # launch, and through `setup` before every launch of a search. + reset_partials!() + ct.@tuned(search=search, shipped=joinpath(@__DIR__, "tuning"), + key=(GROUP_SIZE_M, nextpow.(2, (M, N))...), setup=cfg -> reset_partials!(), + tile_n=tile_ns, hints=hint_sets) do (; tile_n, hints) + @cuda backend=cuTile blocks=M hints... layer_norm_bwd_dx_partial_dwdb( + DX, DY, DW_partial, DB_partial, X, W, Mean, Rstd, Locks, + ct.Constant(GROUP_SIZE_M), ct.Constant(tile_n)) + end + @cuda backend=cuTile blocks=cld(N, TILE_N_DWDB) layer_norm_bwd_dwdb( + DW_partial, DB_partial, FINAL_DW, FINAL_DB, ct.Constant(TILE_M), ct.Constant(TILE_N_DWDB)) + end + + # the first calls compile, and search if asked to + run_fwd() + run_bwd() # Warmup CUDA.@sync for _ in 1:warmup run_fwd() @@ -316,11 +343,11 @@ function verify(data, result) @assert isapprox(expected_DB, Array(result.FINAL_DB); rtol=1e-2) "dB mismatch" end -function test_layernorm(M, N, TILE_N; TILE_M::Int=32, eps::Float32=1f-5, name=nothing) - name = something(name, "layernorm ($M x $N), tile_n=$TILE_N, tile_m=$TILE_M") +function test_layernorm(M, N; eps::Float32=1f-5, name=nothing) + name = something(name, "layernorm ($M x $N)") println("--- $name ---") data = prepare(; M, N, eps) - result = run(data; TILE_N, TILE_M) + result = run(data) verify(data, result) println(" fwd passed, bwd passed") end @@ -344,9 +371,9 @@ end function main() println("=== cuTile LayerNorm Examples (fwd+bwd) ===\n") - test_layernorm(256, 256, 256) - test_layernorm(512, 512, 512) - test_layernorm(1024, 1024, 1024) + test_layernorm(256, 256) + test_layernorm(512, 512) + test_layernorm(1024, 1024) println("\n=== All layernorm examples completed ===") end diff --git a/examples/matmul.jl b/examples/matmul.jl index e34600a07..583610404 100644 --- a/examples/matmul.jl +++ b/examples/matmul.jl @@ -27,7 +27,7 @@ end # C = A @ B where A is (M, K), B is (K, N), C is (M, N) function matmul_kernel(A::ct.TileArray{T,2}, B::ct.TileArray{T,2}, C::ct.TileArray{T,2}, tm::Int, tn::Int, tk::Int) where {T} - # On sm_120, targeting two CTAs per SM is faster with the default tile sizes in `run`, + # On sm_120, targeting two CTAs per SM is faster with the default tile sizes of `matmul!`, # but slower with larger tiles (e.g. TF32 with tk=64). ct.@compiler_options num_ctas=ct.ByTarget(v"10.0" => 2) occupancy=ct.ByTarget(v"12.0" => 2) # Use 1D grid with swizzle for better cache locality @@ -61,6 +61,36 @@ function matmul_kernel(A::ct.TileArray{T,2}, B::ct.TileArray{T,2}, C::ct.TileArr return nothing end +#============================================================================= + Host-side wrapper +=============================================================================# + +# C = A * B with the given tile sizes. `hints` are compiler hints for the launch, such as +# `occupancy`, overriding the kernel's `@compiler_options`. +function matmul!(C, A, B, tm, tn, tk; hints...) + M, N = size(C) + @cuda backend=cuTile blocks=cld(M, tm) * cld(N, tn) hints... matmul_kernel( + A, B, C, ct.Constant(tm), ct.Constant(tn), ct.Constant(tk)) + return C +end + +# C = A * B with the tile sizes and hints that tuning found for this GPU (see the +# Performance chapter of the manual), or else the first of each: 128x128 output tiles +# that span 128 bytes along K (64 elements for 2-byte types, 32 for Float32 as TF32), +# and the kernel's own hints. With `search=true`, a launch without a tuning record +# first tries every combination and records the fastest. +function matmul!(C, A, B; search::Bool=false) + M, N = size(C) + K = size(A, 2) + tk = eltype(A) === Float32 ? (32, 16, 64) : (64, 32, 16) + ct.@tuned(search=search, shipped=joinpath(@__DIR__, "tuning"), + key=nextpow.(2, (M, N, K)), + tm=(128, 64, 256), tn=(128, 64, 256), tk=tk, + hints=((;), (occupancy=1,), (occupancy=2,), (occupancy=4,))) do (; tm, tn, tk, hints) + matmul!(C, A, B, tm, tn, tk; hints...) + end +end + #============================================================================= Example harness =============================================================================# @@ -78,19 +108,20 @@ function prepare(; benchmark::Bool=false, ) end -# `tk` makes tiles span 128 bytes along K: 64 elements for 2-byte types, 32 for Float32 (TF32) -function run(data; tm::Int=128, tn::Int=128, tk::Int=eltype(data.A) === Float32 ? 32 : 64, - nruns::Int=1, warmup::Int=0) - (; A, B, C, M, N, K) = data - grid = cld(M, tm) * cld(N, tn) +function run(data; search::Bool=false, nruns::Int=1, warmup::Int=0) + (; A, B, C) = data - @cuda backend=cuTile blocks=grid matmul_kernel(A, B, C, ct.Constant(tm), ct.Constant(tn), ct.Constant(tk)) + # the first call compiles, and searches if asked to + matmul!(C, A, B; search) + CUDA.@sync for _ in 1:warmup + matmul!(C, A, B; search) + end times = Float64[] NVTX.@range "cuTile" begin for i in 1:nruns NVTX.@range "run $i" begin - t = CUDA.@elapsed @cuda backend=cuTile blocks=grid matmul_kernel(A, B, C, ct.Constant(tm), ct.Constant(tn), ct.Constant(tk)) + t = CUDA.@elapsed matmul!(C, A, B; search) push!(times, t * 1000) # ms end end @@ -148,11 +179,16 @@ end Main =============================================================================# -function test_matmul(::Type{T}, M, N, K, tm, tn, tk; name=nothing) where T - name = something(name, "matmul ($M x $K) @ ($K x $N), $T, tiles=$tm x $tn x $tk") +function test_matmul(::Type{T}, M, N, K, tiles=nothing; name=nothing) where T + name = something(name, "matmul ($M x $K) @ ($K x $N), $T, " * + (tiles === nothing ? "tuned tiles" : "tiles=$(join(tiles, " x "))")) println("--- $name ---") data = prepare(; M, N, K, T) - result = run(data; tm, tn, tk) + result = if tiles === nothing + run(data) + else + (; C=matmul!(data.C, data.A, data.B, tiles...)) + end verify(data, result) println(" passed") end @@ -160,10 +196,12 @@ end function main() println("--- cuTile Matrix Multiplication Examples ---\n") - test_matmul(Float32, 256, 256, 256, 32, 32, 32) - test_matmul(Float32, 512, 512, 512, 64, 64, 64) - test_matmul(Float32, 256, 512, 128, 32, 32, 32) - test_matmul(Float32, 1024, 1024, 1024, 64, 64, 64) + test_matmul(Float32, 256, 256, 256) + test_matmul(Float16, 256, 256, 256) + test_matmul(Float32, 256, 256, 256, (32, 32, 32)) + test_matmul(Float32, 512, 512, 512, (64, 64, 64)) + test_matmul(Float32, 256, 512, 128, (32, 32, 32)) + test_matmul(Float32, 1024, 1024, 1024, (64, 64, 64)) println("\n--- All matmul examples completed ---") end diff --git a/examples/moe.jl b/examples/moe.jl index 85157f93e..92b274b02 100644 --- a/examples/moe.jl +++ b/examples/moe.jl @@ -185,19 +185,35 @@ function moe_align_tile_size(topk_ids::Matrix{Int}, tile_m::Int, num_experts::In end +# `topk_weights` are flattened in Python-style order (slot varies fastest), to match the +# token ids. `tile_m` is fixed by how the tokens were sorted and padded; the other tile +# sizes and the compiler hints are the ones tuning found for this GPU, or else the first +# of each: `tile_n` and `tile_k` as given, and the kernel's own hints. With +# `search=true`, a launch without a tuning record first tries every combination and +# records the fastest. function invoke_fused_moe_kernel(A, B, C, topk_weights, sorted_token_ids, sorted_expert_ids; - mul_routed_weight, num_token_replicas, tile_m, tile_n, tile_k) + mul_routed_weight, num_token_replicas, tile_m, tile_n, tile_k, + search=false) m = length(sorted_token_ids) n = size(B, 2) - grid = cld(m, tile_m) * cld(n, tile_n) - - # Flatten in Python-style order (slot varies fastest) to match token_id ordering - topk_weights_flat = vec(permutedims(topk_weights)) # C is 3D (dim, topk, num_tokens) → flatten last two dims to (dim, total_tokens) C_flat = reshape(C, size(C, 1), size(C, 2) * size(C, 3)) - @cuda backend=cuTile blocks=grid fused_moe_kernel(A, B, C_flat, topk_weights_flat, sorted_token_ids, sorted_expert_ids, num_token_replicas, ct.Constant(mul_routed_weight), ct.Constant(tile_m), ct.Constant(tile_n), ct.Constant(tile_k)) + # Both matmuls of `cutile_moe` launch from here, and tuning choices are remembered + # per call site for the session: `key` tells them apart, by the constants that can + # differ between calls and by the shapes. + ct.@tuned(search=search, shipped=joinpath(@__DIR__, "tuning"), + key=(mul_routed_weight, tile_m, size(A), size(B)), + tile_n=unique((tile_n, 64, 128)), tile_k=unique((tile_k, 32, 64, 128)), + hints=((;), (occupancy=1,), (occupancy=2,), (occupancy=4,), + (num_worker_warps=8,), (occupancy=2, num_worker_warps=8))) do (; tile_n, tile_k, hints) + grid = cld(m, tile_m) * cld(n, tile_n) + @cuda backend=cuTile blocks=grid hints... fused_moe_kernel( + A, B, C_flat, topk_weights, sorted_token_ids, sorted_expert_ids, num_token_replicas, + ct.Constant(mul_routed_weight), ct.Constant(tile_m), ct.Constant(tile_n), + ct.Constant(tile_k)) + end end @@ -218,7 +234,7 @@ end function cutile_moe(hidden_states::CuArray{T}, w1, w2, topk_weights, topk_ids, - tile_m, tile_n, tile_k) where {T} + tile_m, tile_n, tile_k; search::Bool=false) where {T} hidden_size, num_tokens = size(hidden_states) # (hidden, num_tokens) intermediate_size = size(w2, 1) # w2 is (inter, hidden, experts) num_experts = size(w1, 3) @@ -233,13 +249,14 @@ function cutile_moe(hidden_states::CuArray{T}, w1, w2, topk_weights, topk_ids, sorted_token_ids, sorted_expert_ids = moe_align_tile_size( Array(topk_ids), tile_m, num_experts) + topk_weights_flat = vec(permutedims(topk_weights)) # First matmul: hidden_states @ w1^T → gate+up projection invoke_fused_moe_kernel( hidden_states, w1, cache1, - topk_weights, sorted_token_ids, sorted_expert_ids; + topk_weights_flat, sorted_token_ids, sorted_expert_ids; mul_routed_weight=false, num_token_replicas=topk, - tile_m, tile_n, tile_k) + tile_m, tile_n, tile_k, search) # SiLU activation: SiLU(gate) * up # cache1 is (inter*2, topk, num_tokens) → flatten to (inter*2, total_tokens) @@ -249,9 +266,9 @@ function cutile_moe(hidden_states::CuArray{T}, w1, w2, topk_weights, topk_ids, # Second matmul: activated @ w2^T → down projection, with routing weights invoke_fused_moe_kernel( cache2, w2, cache3, - topk_weights, sorted_token_ids, sorted_expert_ids; + topk_weights_flat, sorted_token_ids, sorted_expert_ids; mul_routed_weight=true, num_token_replicas=1, - tile_m, tile_n, tile_k) + tile_m, tile_n, tile_k, search) # Sum over topk slots (second dimension) for each token # cache3 is (hidden, topk, num_tokens) → sum over topk @@ -344,21 +361,24 @@ function prepare(; benchmark::Bool=false, end -function run(data; nruns::Int=1, warmup::Int=0) +function run(data; search::Bool=false, nruns::Int=1, warmup::Int=0) (; hidden_states, w1, w2, topk_weights, topk_ids, tile_m, tile_n, tile_k) = data + # the first call compiles, and searches if asked to + out = cutile_moe(hidden_states, w1, w2, topk_weights, topk_ids, tile_m, tile_n, tile_k; + search) CUDA.@sync for _ in 1:warmup - cutile_moe(hidden_states, w1, w2, topk_weights, topk_ids, tile_m, tile_n, tile_k) + cutile_moe(hidden_states, w1, w2, topk_weights, topk_ids, tile_m, tile_n, tile_k; + search) end times = Float64[] - out = nothing NVTX.@range "cuTile" begin for i in 1:nruns NVTX.@range "run $i" begin t = CUDA.@elapsed begin out = cutile_moe(hidden_states, w1, w2, topk_weights, topk_ids, - tile_m, tile_n, tile_k) + tile_m, tile_n, tile_k; search) end push!(times, t * 1000) # ms end diff --git a/examples/tuning/342c7e4fd995386469a1d97dff264ac3f78deaf6cc8f5d3ac2be0871f38785e0.NVIDIA_GeForce_RTX_5080.toml b/examples/tuning/342c7e4fd995386469a1d97dff264ac3f78deaf6cc8f5d3ac2be0871f38785e0.NVIDIA_GeForce_RTX_5080.toml new file mode 100644 index 000000000..9f8ae9b75 --- /dev/null +++ b/examples/tuning/342c7e4fd995386469a1d97dff264ac3f78deaf6cc8f5d3ac2be0871f38785e0.NVIDIA_GeForce_RTX_5080.toml @@ -0,0 +1,59 @@ +capability = "12.0.0" +config = "(tile_n = 4096, hints = NamedTuple())" +cutile = "1.1.0" +date = "2026-12-02T19:13:33" +default_time = 0.000324284 +device = "NVIDIA GeForce RTX 5080" +index = 1 +kernels = "layer_norm_bwd_dx_partial_dwdb" +tileiras = "13.5.37" +time = 0.000324284 + +[[trials]] +config = "(tile_n = 4096, hints = NamedTuple())" +samples = 10 +time = 0.000324284 +[[trials]] +config = "(tile_n = 1024, hints = NamedTuple())" +samples = 1 +time = 0.000766538 +[[trials]] +config = "(tile_n = 2048, hints = NamedTuple())" +samples = 3 +time = 0.000484452 +[[trials]] +config = "(tile_n = 4096, hints = (occupancy = 1,))" +samples = 10 +time = 0.000324805 +[[trials]] +config = "(tile_n = 1024, hints = (occupancy = 1,))" +samples = 1 +time = 0.000766709 +[[trials]] +config = "(tile_n = 2048, hints = (occupancy = 1,))" +samples = 3 +time = 0.000485895 +[[trials]] +config = "(tile_n = 4096, hints = (occupancy = 2,))" +samples = 10 +time = 0.000325025 +[[trials]] +config = "(tile_n = 1024, hints = (occupancy = 2,))" +samples = 3 +time = 0.000602512 +[[trials]] +config = "(tile_n = 2048, hints = (occupancy = 2,))" +samples = 3 +time = 0.000485695 +[[trials]] +config = "(tile_n = 4096, hints = (occupancy = 4,))" +samples = 10 +time = 0.000325196 +[[trials]] +config = "(tile_n = 1024, hints = (occupancy = 4,))" +samples = 1 +time = 0.000768842 +[[trials]] +config = "(tile_n = 2048, hints = (occupancy = 4,))" +samples = 3 +time = 0.000485233 diff --git a/examples/tuning/37c240c85bc53f8ff5d81fdd1a4d037185d5c84bfe28a71b1d6ff1d6af2c3684.NVIDIA_GeForce_RTX_5080.toml b/examples/tuning/37c240c85bc53f8ff5d81fdd1a4d037185d5c84bfe28a71b1d6ff1d6af2c3684.NVIDIA_GeForce_RTX_5080.toml new file mode 100644 index 000000000..a4c6de6ab --- /dev/null +++ b/examples/tuning/37c240c85bc53f8ff5d81fdd1a4d037185d5c84bfe28a71b1d6ff1d6af2c3684.NVIDIA_GeForce_RTX_5080.toml @@ -0,0 +1,443 @@ +capability = "12.0.0" +config = "(tm = 64, tn = 128, tk = 32, hints = NamedTuple())" +cutile = "1.1.0" +date = "2026-12-02T19:05:08" +default_time = 0.00251262 +device = "NVIDIA GeForce RTX 5080" +index = 2 +kernels = "matmul_kernel" +tileiras = "13.5.37" +time = 0.002445145 + +[[trials]] +config = "(tm = 128, tn = 128, tk = 32, hints = NamedTuple())" +samples = 10 +time = 0.00251262 +[[trials]] +config = "(tm = 64, tn = 128, tk = 32, hints = NamedTuple())" +samples = 10 +time = 0.002445145 +[[trials]] +config = "(tm = 256, tn = 128, tk = 32, hints = NamedTuple())" +samples = 1 +time = 0.006360758 +[[trials]] +config = "(tm = 128, tn = 64, tk = 32, hints = NamedTuple())" +samples = 10 +time = 0.002475521 +[[trials]] +config = "(tm = 64, tn = 64, tk = 32, hints = NamedTuple())" +samples = 10 +time = 0.002569516 +[[trials]] +config = "(tm = 256, tn = 64, tk = 32, hints = NamedTuple())" +samples = 10 +time = 0.002574105 +[[trials]] +config = "(tm = 128, tn = 256, tk = 32, hints = NamedTuple())" +samples = 3 +time = 0.004758744 +[[trials]] +config = "(tm = 64, tn = 256, tk = 32, hints = NamedTuple())" +samples = 10 +time = 0.002542306 +[[trials]] +config = "(tm = 256, tn = 256, tk = 32, hints = NamedTuple())" +samples = 1 +time = 0.016458837 +[[trials]] +config = "(tm = 128, tn = 128, tk = 16, hints = NamedTuple())" +samples = 10 +time = 0.002647231 +[[trials]] +config = "(tm = 64, tn = 128, tk = 16, hints = NamedTuple())" +samples = 10 +time = 0.002502792 +[[trials]] +config = "(tm = 256, tn = 128, tk = 16, hints = NamedTuple())" +samples = 1 +time = 0.008359511 +[[trials]] +config = "(tm = 128, tn = 64, tk = 16, hints = NamedTuple())" +samples = 10 +time = 0.002497612 +[[trials]] +config = "(tm = 64, tn = 64, tk = 16, hints = NamedTuple())" +samples = 10 +time = 0.002512279 +[[trials]] +config = "(tm = 256, tn = 64, tk = 16, hints = NamedTuple())" +samples = 10 +time = 0.002587961 +[[trials]] +config = "(tm = 128, tn = 256, tk = 16, hints = NamedTuple())" +samples = 1 +time = 0.006409218 +[[trials]] +config = "(tm = 64, tn = 256, tk = 16, hints = NamedTuple())" +samples = 10 +time = 0.003004366 +[[trials]] +config = "(tm = 256, tn = 256, tk = 16, hints = NamedTuple())" +samples = 1 +time = 0.024643212 +[[trials]] +config = "(tm = 128, tn = 128, tk = 64, hints = NamedTuple())" +samples = 3 +time = 0.003810207 +[[trials]] +config = "(tm = 64, tn = 128, tk = 64, hints = NamedTuple())" +samples = 10 +time = 0.002669883 +[[trials]] +config = "(tm = 256, tn = 128, tk = 64, hints = NamedTuple())" +samples = 3 +time = 0.004805091 +[[trials]] +config = "(tm = 128, tn = 64, tk = 64, hints = NamedTuple())" +samples = 10 +time = 0.00252847 +[[trials]] +config = "(tm = 64, tn = 64, tk = 64, hints = NamedTuple())" +samples = 10 +time = 0.002490068 +[[trials]] +config = "(tm = 256, tn = 64, tk = 64, hints = NamedTuple())" +samples = 1 +time = 0.005103136 +[[trials]] +config = "(tm = 128, tn = 256, tk = 64, hints = NamedTuple())" +samples = 3 +time = 0.004124353 +[[trials]] +config = "(tm = 64, tn = 256, tk = 64, hints = NamedTuple())" +samples = 10 +time = 0.002891136 +[[trials]] +config = "(tm = 256, tn = 256, tk = 64, hints = NamedTuple())" +samples = 1 +time = 0.007606519 +[[trials]] +config = "(tm = 128, tn = 128, tk = 32, hints = (occupancy = 1,))" +samples = 10 +time = 0.002567442 +[[trials]] +config = "(tm = 64, tn = 128, tk = 32, hints = (occupancy = 1,))" +samples = 10 +time = 0.002815324 +[[trials]] +config = "(tm = 256, tn = 128, tk = 32, hints = (occupancy = 1,))" +samples = 1 +time = 0.005483774 +[[trials]] +config = "(tm = 128, tn = 64, tk = 32, hints = (occupancy = 1,))" +samples = 10 +time = 0.002748309 +[[trials]] +config = "(tm = 64, tn = 64, tk = 32, hints = (occupancy = 1,))" +samples = 10 +time = 0.002836463 +[[trials]] +config = "(tm = 256, tn = 64, tk = 32, hints = (occupancy = 1,))" +samples = 10 +time = 0.002721409 +[[trials]] +config = "(tm = 128, tn = 256, tk = 32, hints = (occupancy = 1,))" +samples = 10 +time = 0.002820143 +[[trials]] +config = "(tm = 64, tn = 256, tk = 32, hints = (occupancy = 1,))" +samples = 10 +time = 0.002725707 +[[trials]] +config = "(tm = 256, tn = 256, tk = 32, hints = (occupancy = 1,))" +samples = 1 +time = 0.008606321 +[[trials]] +config = "(tm = 128, tn = 128, tk = 16, hints = (occupancy = 1,))" +samples = 10 +time = 0.002552614 +[[trials]] +config = "(tm = 64, tn = 128, tk = 16, hints = (occupancy = 1,))" +samples = 10 +time = 0.00278083 +[[trials]] +config = "(tm = 256, tn = 128, tk = 16, hints = (occupancy = 1,))" +samples = 3 +time = 0.004286905 +[[trials]] +config = "(tm = 128, tn = 64, tk = 16, hints = (occupancy = 1,))" +samples = 10 +time = 0.002938333 +[[trials]] +config = "(tm = 64, tn = 64, tk = 16, hints = (occupancy = 1,))" +samples = 10 +time = 0.003036917 +[[trials]] +config = "(tm = 256, tn = 64, tk = 16, hints = (occupancy = 1,))" +samples = 10 +time = 0.002884834 +[[trials]] +config = "(tm = 128, tn = 256, tk = 16, hints = (occupancy = 1,))" +samples = 10 +time = 0.002869455 +[[trials]] +config = "(tm = 64, tn = 256, tk = 16, hints = (occupancy = 1,))" +samples = 10 +time = 0.002653313 +[[trials]] +config = "(tm = 256, tn = 256, tk = 16, hints = (occupancy = 1,))" +samples = 1 +time = 0.014236347 +[[trials]] +config = "(tm = 128, tn = 128, tk = 64, hints = (occupancy = 1,))" +samples = 10 +time = 0.002608548 +[[trials]] +config = "(tm = 64, tn = 128, tk = 64, hints = (occupancy = 1,))" +samples = 3 +time = 0.003338749 +[[trials]] +config = "(tm = 256, tn = 128, tk = 64, hints = (occupancy = 1,))" +samples = 3 +time = 0.004469416 +[[trials]] +config = "(tm = 128, tn = 64, tk = 64, hints = (occupancy = 1,))" +samples = 10 +time = 0.002670114 +[[trials]] +config = "(tm = 64, tn = 64, tk = 64, hints = (occupancy = 1,))" +samples = 10 +time = 0.002891796 +[[trials]] +config = "(tm = 256, tn = 64, tk = 64, hints = (occupancy = 1,))" +samples = 3 +time = 0.003503065 +[[trials]] +config = "(tm = 128, tn = 256, tk = 64, hints = (occupancy = 1,))" +samples = 3 +time = 0.004107952 +[[trials]] +config = "(tm = 64, tn = 256, tk = 64, hints = (occupancy = 1,))" +samples = 10 +time = 0.002898559 +[[trials]] +config = "(tm = 256, tn = 256, tk = 64, hints = (occupancy = 1,))" +samples = 1 +time = 0.007573276 +[[trials]] +config = "(tm = 128, tn = 128, tk = 32, hints = (occupancy = 2,))" +samples = 10 +time = 0.002515465 +[[trials]] +config = "(tm = 64, tn = 128, tk = 32, hints = (occupancy = 2,))" +samples = 10 +time = 0.002447709 +[[trials]] +config = "(tm = 256, tn = 128, tk = 32, hints = (occupancy = 2,))" +samples = 1 +time = 0.006376287 +[[trials]] +config = "(tm = 128, tn = 64, tk = 32, hints = (occupancy = 2,))" +samples = 10 +time = 0.002476252 +[[trials]] +config = "(tm = 64, tn = 64, tk = 32, hints = (occupancy = 2,))" +samples = 10 +time = 0.002569116 +[[trials]] +config = "(tm = 256, tn = 64, tk = 32, hints = (occupancy = 2,))" +samples = 10 +time = 0.002568384 +[[trials]] +config = "(tm = 128, tn = 256, tk = 32, hints = (occupancy = 2,))" +samples = 3 +time = 0.004772239 +[[trials]] +config = "(tm = 64, tn = 256, tk = 32, hints = (occupancy = 2,))" +samples = 10 +time = 0.002545352 +[[trials]] +config = "(tm = 256, tn = 256, tk = 32, hints = (occupancy = 2,))" +samples = 1 +time = 0.016575495 +[[trials]] +config = "(tm = 128, tn = 128, tk = 16, hints = (occupancy = 2,))" +samples = 10 +time = 0.002649495 +[[trials]] +config = "(tm = 64, tn = 128, tk = 16, hints = (occupancy = 2,))" +samples = 10 +time = 0.002499857 +[[trials]] +config = "(tm = 256, tn = 128, tk = 16, hints = (occupancy = 2,))" +samples = 1 +time = 0.008308516 +[[trials]] +config = "(tm = 128, tn = 64, tk = 16, hints = (occupancy = 2,))" +samples = 10 +time = 0.002501459 +[[trials]] +config = "(tm = 64, tn = 64, tk = 16, hints = (occupancy = 2,))" +samples = 10 +time = 0.002514394 +[[trials]] +config = "(tm = 256, tn = 64, tk = 16, hints = (occupancy = 2,))" +samples = 10 +time = 0.002594182 +[[trials]] +config = "(tm = 128, tn = 256, tk = 16, hints = (occupancy = 2,))" +samples = 1 +time = 0.006404319 +[[trials]] +config = "(tm = 64, tn = 256, tk = 16, hints = (occupancy = 2,))" +samples = 10 +time = 0.003007532 +[[trials]] +config = "(tm = 256, tn = 256, tk = 16, hints = (occupancy = 2,))" +samples = 1 +time = 0.024678177 +[[trials]] +config = "(tm = 128, tn = 128, tk = 64, hints = (occupancy = 2,))" +samples = 3 +time = 0.003815937 +[[trials]] +config = "(tm = 64, tn = 128, tk = 64, hints = (occupancy = 2,))" +samples = 10 +time = 0.002667228 +[[trials]] +config = "(tm = 256, tn = 128, tk = 64, hints = (occupancy = 2,))" +samples = 3 +time = 0.004739909 +[[trials]] +config = "(tm = 128, tn = 64, tk = 64, hints = (occupancy = 2,))" +samples = 10 +time = 0.002496891 +[[trials]] +config = "(tm = 64, tn = 64, tk = 64, hints = (occupancy = 2,))" +samples = 10 +time = 0.002472926 +[[trials]] +config = "(tm = 256, tn = 64, tk = 64, hints = (occupancy = 2,))" +samples = 1 +time = 0.005089991 +[[trials]] +config = "(tm = 128, tn = 256, tk = 64, hints = (occupancy = 2,))" +samples = 3 +time = 0.004114204 +[[trials]] +config = "(tm = 64, tn = 256, tk = 64, hints = (occupancy = 2,))" +samples = 10 +time = 0.002878341 +[[trials]] +config = "(tm = 256, tn = 256, tk = 64, hints = (occupancy = 2,))" +samples = 1 +time = 0.007583615 +[[trials]] +config = "(tm = 128, tn = 128, tk = 32, hints = (occupancy = 4,))" +samples = 1 +time = 0.006788855 +[[trials]] +config = "(tm = 64, tn = 128, tk = 32, hints = (occupancy = 4,))" +samples = 10 +time = 0.002711962 +[[trials]] +config = "(tm = 256, tn = 128, tk = 32, hints = (occupancy = 4,))" +samples = 1 +time = 0.042781558 +[[trials]] +config = "(tm = 128, tn = 64, tk = 32, hints = (occupancy = 4,))" +samples = 10 +time = 0.002799083 +[[trials]] +config = "(tm = 64, tn = 64, tk = 32, hints = (occupancy = 4,))" +samples = 10 +time = 0.002984279 +[[trials]] +config = "(tm = 256, tn = 64, tk = 32, hints = (occupancy = 4,))" +samples = 1 +time = 0.007852266 +[[trials]] +config = "(tm = 128, tn = 256, tk = 32, hints = (occupancy = 4,))" +samples = 1 +time = 0.014069918 +[[trials]] +config = "(tm = 64, tn = 256, tk = 32, hints = (occupancy = 4,))" +samples = 1 +time = 0.007233854 +[[trials]] +config = "(tm = 256, tn = 256, tk = 32, hints = (occupancy = 4,))" +samples = 1 +time = 0.064716435 +[[trials]] +config = "(tm = 128, tn = 128, tk = 16, hints = (occupancy = 4,))" +samples = 1 +time = 0.013231956 +[[trials]] +config = "(tm = 64, tn = 128, tk = 16, hints = (occupancy = 4,))" +samples = 10 +time = 0.002546644 +[[trials]] +config = "(tm = 256, tn = 128, tk = 16, hints = (occupancy = 4,))" +samples = 1 +time = 0.045648087 +[[trials]] +config = "(tm = 128, tn = 64, tk = 16, hints = (occupancy = 4,))" +samples = 10 +time = 0.002482935 +[[trials]] +config = "(tm = 64, tn = 64, tk = 16, hints = (occupancy = 4,))" +samples = 10 +time = 0.002515936 +[[trials]] +config = "(tm = 256, tn = 64, tk = 16, hints = (occupancy = 4,))" +samples = 1 +time = 0.025889754 +[[trials]] +config = "(tm = 128, tn = 256, tk = 16, hints = (occupancy = 4,))" +samples = 1 +time = 0.020995227 +[[trials]] +config = "(tm = 64, tn = 256, tk = 16, hints = (occupancy = 4,))" +samples = 1 +time = 0.014772756 +[[trials]] +config = "(tm = 256, tn = 256, tk = 16, hints = (occupancy = 4,))" +samples = 1 +time = 0.081747257 +[[trials]] +config = "(tm = 128, tn = 128, tk = 64, hints = (occupancy = 4,))" +samples = 10 +time = 0.002610502 +[[trials]] +config = "(tm = 64, tn = 128, tk = 64, hints = (occupancy = 4,))" +samples = 3 +time = 0.003332698 +[[trials]] +config = "(tm = 256, tn = 128, tk = 64, hints = (occupancy = 4,))" +samples = 3 +time = 0.004476859 +[[trials]] +config = "(tm = 128, tn = 64, tk = 64, hints = (occupancy = 4,))" +samples = 10 +time = 0.002671617 +[[trials]] +config = "(tm = 64, tn = 64, tk = 64, hints = (occupancy = 4,))" +samples = 10 +time = 0.002895724 +[[trials]] +config = "(tm = 256, tn = 64, tk = 64, hints = (occupancy = 4,))" +samples = 3 +time = 0.003507454 +[[trials]] +config = "(tm = 128, tn = 256, tk = 64, hints = (occupancy = 4,))" +samples = 3 +time = 0.004113612 +[[trials]] +config = "(tm = 64, tn = 256, tk = 64, hints = (occupancy = 4,))" +samples = 10 +time = 0.002896415 +[[trials]] +config = "(tm = 256, tn = 256, tk = 64, hints = (occupancy = 4,))" +samples = 1 +time = 0.007578286 diff --git a/examples/tuning/5e8e1d06be811461700dea5884ee38ee240cb3ff0415dcefec56d12d3c73c096.NVIDIA_GeForce_RTX_5080.toml b/examples/tuning/5e8e1d06be811461700dea5884ee38ee240cb3ff0415dcefec56d12d3c73c096.NVIDIA_GeForce_RTX_5080.toml new file mode 100644 index 000000000..daf78d77e --- /dev/null +++ b/examples/tuning/5e8e1d06be811461700dea5884ee38ee240cb3ff0415dcefec56d12d3c73c096.NVIDIA_GeForce_RTX_5080.toml @@ -0,0 +1,155 @@ +capability = "12.0.0" +config = "(tile_n = 64, tile_k = 64, hints = NamedTuple())" +cutile = "1.1.0" +date = "2026-12-02T19:13:27" +default_time = 0.00022093799999999998 +device = "NVIDIA GeForce RTX 5080" +index = 2 +kernels = "fused_moe_kernel" +tileiras = "13.5.37" +time = 0.000201325 + +[[trials]] +config = "(tile_n = 128, tile_k = 64, hints = NamedTuple())" +samples = 10 +time = 0.00022093799999999998 +[[trials]] +config = "(tile_n = 64, tile_k = 64, hints = NamedTuple())" +samples = 10 +time = 0.000201325 +[[trials]] +config = "(tile_n = 128, tile_k = 32, hints = NamedTuple())" +samples = 10 +time = 0.00022726333333333336 +[[trials]] +config = "(tile_n = 64, tile_k = 32, hints = NamedTuple())" +samples = 10 +time = 0.00020393475 +[[trials]] +config = "(tile_n = 128, tile_k = 128, hints = NamedTuple())" +samples = 3 +time = 0.00025237666666666665 +[[trials]] +config = "(tile_n = 64, tile_k = 128, hints = NamedTuple())" +samples = 3 +time = 0.000250697 +[[trials]] +config = "(tile_n = 128, tile_k = 64, hints = (occupancy = 1,))" +samples = 3 +time = 0.0003261775 +[[trials]] +config = "(tile_n = 64, tile_k = 64, hints = (occupancy = 1,))" +samples = 10 +time = 0.0002056455 +[[trials]] +config = "(tile_n = 128, tile_k = 32, hints = (occupancy = 1,))" +samples = 3 +time = 0.00026403166666666666 +[[trials]] +config = "(tile_n = 64, tile_k = 32, hints = (occupancy = 1,))" +samples = 10 +time = 0.00021991975 +[[trials]] +config = "(tile_n = 128, tile_k = 128, hints = (occupancy = 1,))" +samples = 3 +time = 0.0003485895 +[[trials]] +config = "(tile_n = 64, tile_k = 128, hints = (occupancy = 1,))" +samples = 3 +time = 0.0002644223333333333 +[[trials]] +config = "(tile_n = 128, tile_k = 64, hints = (occupancy = 2,))" +samples = 10 +time = 0.00021916825 +[[trials]] +config = "(tile_n = 64, tile_k = 64, hints = (occupancy = 2,))" +samples = 10 +time = 0.000199797 +[[trials]] +config = "(tile_n = 128, tile_k = 32, hints = (occupancy = 2,))" +samples = 10 +time = 0.0002257705 +[[trials]] +config = "(tile_n = 64, tile_k = 32, hints = (occupancy = 2,))" +samples = 10 +time = 0.0002047415 +[[trials]] +config = "(tile_n = 128, tile_k = 128, hints = (occupancy = 2,))" +samples = 3 +time = 0.00025193599999999997 +[[trials]] +config = "(tile_n = 64, tile_k = 128, hints = (occupancy = 2,))" +samples = 3 +time = 0.00025624066666666667 +[[trials]] +config = "(tile_n = 128, tile_k = 64, hints = (occupancy = 4,))" +samples = 3 +time = 0.000324725 +[[trials]] +config = "(tile_n = 64, tile_k = 64, hints = (occupancy = 4,))" +samples = 10 +time = 0.00020518975 +[[trials]] +config = "(tile_n = 128, tile_k = 32, hints = (occupancy = 4,))" +samples = 1 +time = 0.000761237 +[[trials]] +config = "(tile_n = 64, tile_k = 32, hints = (occupancy = 4,))" +samples = 10 +time = 0.000224601 +[[trials]] +config = "(tile_n = 128, tile_k = 128, hints = (occupancy = 4,))" +samples = 3 +time = 0.0003464905 +[[trials]] +config = "(tile_n = 64, tile_k = 128, hints = (occupancy = 4,))" +samples = 3 +time = 0.000262973 +[[trials]] +config = "(tile_n = 128, tile_k = 64, hints = (num_worker_warps = 8,))" +samples = 10 +time = 0.0002448726666666667 +[[trials]] +config = "(tile_n = 64, tile_k = 64, hints = (num_worker_warps = 8,))" +samples = 10 +time = 0.00020553525 +[[trials]] +config = "(tile_n = 128, tile_k = 32, hints = (num_worker_warps = 8,))" +samples = 10 +time = 0.0002338005 +[[trials]] +config = "(tile_n = 64, tile_k = 32, hints = (num_worker_warps = 8,))" +samples = 10 +time = 0.000210908 +[[trials]] +config = "(tile_n = 128, tile_k = 128, hints = (num_worker_warps = 8,))" +samples = 3 +time = 0.000252263 +[[trials]] +config = "(tile_n = 64, tile_k = 128, hints = (num_worker_warps = 8,))" +samples = 10 +time = 0.00023312425 +[[trials]] +config = "(tile_n = 128, tile_k = 64, hints = (occupancy = 2, num_worker_warps = 8))" +samples = 10 +time = 0.0002432733333333333 +[[trials]] +config = "(tile_n = 64, tile_k = 64, hints = (occupancy = 2, num_worker_warps = 8))" +samples = 10 +time = 0.00020519225 +[[trials]] +config = "(tile_n = 128, tile_k = 32, hints = (occupancy = 2, num_worker_warps = 8))" +samples = 10 +time = 0.000233595 +[[trials]] +config = "(tile_n = 64, tile_k = 32, hints = (occupancy = 2, num_worker_warps = 8))" +samples = 10 +time = 0.00021082 +[[trials]] +config = "(tile_n = 128, tile_k = 128, hints = (occupancy = 2, num_worker_warps = 8))" +samples = 3 +time = 0.00025126799999999997 +[[trials]] +config = "(tile_n = 64, tile_k = 128, hints = (occupancy = 2, num_worker_warps = 8))" +samples = 10 +time = 0.0002322875 diff --git a/examples/tuning/89a29e1d9bb3f926453aee566deccd33e52b6b3bceb70d6d35bf29eb5136ea05.NVIDIA_GeForce_RTX_5080.toml b/examples/tuning/89a29e1d9bb3f926453aee566deccd33e52b6b3bceb70d6d35bf29eb5136ea05.NVIDIA_GeForce_RTX_5080.toml new file mode 100644 index 000000000..a422b1577 --- /dev/null +++ b/examples/tuning/89a29e1d9bb3f926453aee566deccd33e52b6b3bceb70d6d35bf29eb5136ea05.NVIDIA_GeForce_RTX_5080.toml @@ -0,0 +1,443 @@ +capability = "12.0.0" +config = "(tm = 64, tn = 128, tk = 16, hints = (occupancy = 4,))" +cutile = "1.1.0" +date = "2026-12-02T19:05:21" +default_time = 0.000333236 +device = "NVIDIA GeForce RTX 5080" +index = 92 +kernels = "batch_matmul_kernel" +tileiras = "13.5.37" +time = 0.000322596 + +[[trials]] +config = "(tm = 128, tn = 128, tk = 32, hints = NamedTuple())" +samples = 10 +time = 0.000333236 +[[trials]] +config = "(tm = 64, tn = 128, tk = 32, hints = NamedTuple())" +samples = 10 +time = 0.000343375 +[[trials]] +config = "(tm = 256, tn = 128, tk = 32, hints = NamedTuple())" +samples = 1 +time = 0.000777889 +[[trials]] +config = "(tm = 128, tn = 64, tk = 32, hints = NamedTuple())" +samples = 10 +time = 0.00034088 +[[trials]] +config = "(tm = 64, tn = 64, tk = 32, hints = NamedTuple())" +samples = 10 +time = 0.0003830335 +[[trials]] +config = "(tm = 256, tn = 64, tk = 32, hints = NamedTuple())" +samples = 10 +time = 0.000387717 +[[trials]] +config = "(tm = 128, tn = 256, tk = 32, hints = NamedTuple())" +samples = 1 +time = 0.000717486 +[[trials]] +config = "(tm = 64, tn = 256, tk = 32, hints = NamedTuple())" +samples = 10 +time = 0.000342653 +[[trials]] +config = "(tm = 256, tn = 256, tk = 32, hints = NamedTuple())" +samples = 1 +time = 0.002562132 +[[trials]] +config = "(tm = 128, tn = 128, tk = 16, hints = NamedTuple())" +samples = 10 +time = 0.0003319635 +[[trials]] +config = "(tm = 64, tn = 128, tk = 16, hints = NamedTuple())" +samples = 10 +time = 0.0003431795 +[[trials]] +config = "(tm = 256, tn = 128, tk = 16, hints = NamedTuple())" +samples = 1 +time = 0.001107173 +[[trials]] +config = "(tm = 128, tn = 64, tk = 16, hints = NamedTuple())" +samples = 10 +time = 0.000346155 +[[trials]] +config = "(tm = 64, tn = 64, tk = 16, hints = NamedTuple())" +samples = 10 +time = 0.0003775385 +[[trials]] +config = "(tm = 256, tn = 64, tk = 16, hints = NamedTuple())" +samples = 10 +time = 0.0003467205 +[[trials]] +config = "(tm = 128, tn = 256, tk = 16, hints = NamedTuple())" +samples = 1 +time = 0.000869129 +[[trials]] +config = "(tm = 64, tn = 256, tk = 16, hints = NamedTuple())" +samples = 10 +time = 0.0003486545 +[[trials]] +config = "(tm = 256, tn = 256, tk = 16, hints = NamedTuple())" +samples = 1 +time = 0.00356977 +[[trials]] +config = "(tm = 128, tn = 128, tk = 64, hints = NamedTuple())" +samples = 3 +time = 0.000514368 +[[trials]] +config = "(tm = 64, tn = 128, tk = 64, hints = NamedTuple())" +samples = 10 +time = 0.000344276 +[[trials]] +config = "(tm = 256, tn = 128, tk = 64, hints = NamedTuple())" +samples = 1 +time = 0.0009019 +[[trials]] +config = "(tm = 128, tn = 64, tk = 64, hints = NamedTuple())" +samples = 3 +time = 0.0004078545 +[[trials]] +config = "(tm = 64, tn = 64, tk = 64, hints = NamedTuple())" +samples = 10 +time = 0.000373646 +[[trials]] +config = "(tm = 256, tn = 64, tk = 64, hints = NamedTuple())" +samples = 3 +time = 0.000636666 +[[trials]] +config = "(tm = 128, tn = 256, tk = 64, hints = NamedTuple())" +samples = 3 +time = 0.000610146 +[[trials]] +config = "(tm = 64, tn = 256, tk = 64, hints = NamedTuple())" +samples = 3 +time = 0.000501975 +[[trials]] +config = "(tm = 256, tn = 256, tk = 64, hints = NamedTuple())" +samples = 1 +time = 0.001263283 +[[trials]] +config = "(tm = 128, tn = 128, tk = 32, hints = (occupancy = 1,))" +samples = 10 +time = 0.000380709 +[[trials]] +config = "(tm = 64, tn = 128, tk = 32, hints = (occupancy = 1,))" +samples = 3 +time = 0.0004245905 +[[trials]] +config = "(tm = 256, tn = 128, tk = 32, hints = (occupancy = 1,))" +samples = 3 +time = 0.000668846 +[[trials]] +config = "(tm = 128, tn = 64, tk = 32, hints = (occupancy = 1,))" +samples = 3 +time = 0.0004131045 +[[trials]] +config = "(tm = 64, tn = 64, tk = 32, hints = (occupancy = 1,))" +samples = 3 +time = 0.000438006 +[[trials]] +config = "(tm = 256, tn = 64, tk = 32, hints = (occupancy = 1,))" +samples = 3 +time = 0.0004097985 +[[trials]] +config = "(tm = 128, tn = 256, tk = 32, hints = (occupancy = 1,))" +samples = 3 +time = 0.000443301 +[[trials]] +config = "(tm = 64, tn = 256, tk = 32, hints = (occupancy = 1,))" +samples = 3 +time = 0.000439388 +[[trials]] +config = "(tm = 256, tn = 256, tk = 32, hints = (occupancy = 1,))" +samples = 1 +time = 0.001281978 +[[trials]] +config = "(tm = 128, tn = 128, tk = 16, hints = (occupancy = 1,))" +samples = 10 +time = 0.0003858985 +[[trials]] +config = "(tm = 64, tn = 128, tk = 16, hints = (occupancy = 1,))" +samples = 3 +time = 0.000428844 +[[trials]] +config = "(tm = 256, tn = 128, tk = 16, hints = (occupancy = 1,))" +samples = 1 +time = 0.000712056 +[[trials]] +config = "(tm = 128, tn = 64, tk = 16, hints = (occupancy = 1,))" +samples = 3 +time = 0.000440766 +[[trials]] +config = "(tm = 64, tn = 64, tk = 16, hints = (occupancy = 1,))" +samples = 3 +time = 0.000503628 +[[trials]] +config = "(tm = 256, tn = 64, tk = 16, hints = (occupancy = 1,))" +samples = 10 +time = 0.000386475 +[[trials]] +config = "(tm = 128, tn = 256, tk = 16, hints = (occupancy = 1,))" +samples = 3 +time = 0.000452623 +[[trials]] +config = "(tm = 64, tn = 256, tk = 16, hints = (occupancy = 1,))" +samples = 10 +time = 0.000377939 +[[trials]] +config = "(tm = 256, tn = 256, tk = 16, hints = (occupancy = 1,))" +samples = 1 +time = 0.001872929 +[[trials]] +config = "(tm = 128, tn = 128, tk = 64, hints = (occupancy = 1,))" +samples = 3 +time = 0.000516502 +[[trials]] +config = "(tm = 64, tn = 128, tk = 64, hints = (occupancy = 1,))" +samples = 3 +time = 0.000404183 +[[trials]] +config = "(tm = 256, tn = 128, tk = 64, hints = (occupancy = 1,))" +samples = 1 +time = 0.000727635 +[[trials]] +config = "(tm = 128, tn = 64, tk = 64, hints = (occupancy = 1,))" +samples = 3 +time = 0.0004862205 +[[trials]] +config = "(tm = 64, tn = 64, tk = 64, hints = (occupancy = 1,))" +samples = 3 +time = 0.0004674255 +[[trials]] +config = "(tm = 256, tn = 64, tk = 64, hints = (occupancy = 1,))" +samples = 3 +time = 0.000626948 +[[trials]] +config = "(tm = 128, tn = 256, tk = 64, hints = (occupancy = 1,))" +samples = 3 +time = 0.000605568 +[[trials]] +config = "(tm = 64, tn = 256, tk = 64, hints = (occupancy = 1,))" +samples = 3 +time = 0.000487503 +[[trials]] +config = "(tm = 256, tn = 256, tk = 64, hints = (occupancy = 1,))" +samples = 1 +time = 0.001267851 +[[trials]] +config = "(tm = 128, tn = 128, tk = 32, hints = (occupancy = 2,))" +samples = 10 +time = 0.0003352695 +[[trials]] +config = "(tm = 64, tn = 128, tk = 32, hints = (occupancy = 2,))" +samples = 10 +time = 0.0003428085 +[[trials]] +config = "(tm = 256, tn = 128, tk = 32, hints = (occupancy = 2,))" +samples = 1 +time = 0.000788499 +[[trials]] +config = "(tm = 128, tn = 64, tk = 32, hints = (occupancy = 2,))" +samples = 10 +time = 0.0003407295 +[[trials]] +config = "(tm = 64, tn = 64, tk = 32, hints = (occupancy = 2,))" +samples = 10 +time = 0.0003821265 +[[trials]] +config = "(tm = 256, tn = 64, tk = 32, hints = (occupancy = 2,))" +samples = 10 +time = 0.0003883735 +[[trials]] +config = "(tm = 128, tn = 256, tk = 32, hints = (occupancy = 2,))" +samples = 1 +time = 0.000679887 +[[trials]] +config = "(tm = 64, tn = 256, tk = 32, hints = (occupancy = 2,))" +samples = 10 +time = 0.0003433145 +[[trials]] +config = "(tm = 256, tn = 256, tk = 32, hints = (occupancy = 2,))" +samples = 1 +time = 0.002529802 +[[trials]] +config = "(tm = 128, tn = 128, tk = 16, hints = (occupancy = 2,))" +samples = 10 +time = 0.000331613 +[[trials]] +config = "(tm = 64, tn = 128, tk = 16, hints = (occupancy = 2,))" +samples = 10 +time = 0.0003433595 +[[trials]] +config = "(tm = 256, tn = 128, tk = 16, hints = (occupancy = 2,))" +samples = 1 +time = 0.001076846 +[[trials]] +config = "(tm = 128, tn = 64, tk = 16, hints = (occupancy = 2,))" +samples = 10 +time = 0.000346165 +[[trials]] +config = "(tm = 64, tn = 64, tk = 16, hints = (occupancy = 2,))" +samples = 10 +time = 0.000377979 +[[trials]] +config = "(tm = 256, tn = 64, tk = 16, hints = (occupancy = 2,))" +samples = 10 +time = 0.0003460945 +[[trials]] +config = "(tm = 128, tn = 256, tk = 16, hints = (occupancy = 2,))" +samples = 1 +time = 0.000832211 +[[trials]] +config = "(tm = 64, tn = 256, tk = 16, hints = (occupancy = 2,))" +samples = 10 +time = 0.000348314 +[[trials]] +config = "(tm = 256, tn = 256, tk = 16, hints = (occupancy = 2,))" +samples = 1 +time = 0.003535846 +[[trials]] +config = "(tm = 128, tn = 128, tk = 64, hints = (occupancy = 2,))" +samples = 3 +time = 0.000512384 +[[trials]] +config = "(tm = 64, tn = 128, tk = 64, hints = (occupancy = 2,))" +samples = 10 +time = 0.000343906 +[[trials]] +config = "(tm = 256, tn = 128, tk = 64, hints = (occupancy = 2,))" +samples = 1 +time = 0.000865432 +[[trials]] +config = "(tm = 128, tn = 64, tk = 64, hints = (occupancy = 2,))" +samples = 3 +time = 0.0004093975 +[[trials]] +config = "(tm = 64, tn = 64, tk = 64, hints = (occupancy = 2,))" +samples = 10 +time = 0.000373616 +[[trials]] +config = "(tm = 256, tn = 64, tk = 64, hints = (occupancy = 2,))" +samples = 3 +time = 0.000631155 +[[trials]] +config = "(tm = 128, tn = 256, tk = 64, hints = (occupancy = 2,))" +samples = 3 +time = 0.000609255 +[[trials]] +config = "(tm = 64, tn = 256, tk = 64, hints = (occupancy = 2,))" +samples = 3 +time = 0.000486511 +[[trials]] +config = "(tm = 256, tn = 256, tk = 64, hints = (occupancy = 2,))" +samples = 1 +time = 0.001283561 +[[trials]] +config = "(tm = 128, tn = 128, tk = 32, hints = (occupancy = 4,))" +samples = 1 +time = 0.00098763 +[[trials]] +config = "(tm = 64, tn = 128, tk = 32, hints = (occupancy = 4,))" +samples = 10 +time = 0.000372193 +[[trials]] +config = "(tm = 256, tn = 128, tk = 32, hints = (occupancy = 4,))" +samples = 1 +time = 0.004092352 +[[trials]] +config = "(tm = 128, tn = 64, tk = 32, hints = (occupancy = 4,))" +samples = 10 +time = 0.000378505 +[[trials]] +config = "(tm = 64, tn = 64, tk = 32, hints = (occupancy = 4,))" +samples = 3 +time = 0.00044832 +[[trials]] +config = "(tm = 256, tn = 64, tk = 32, hints = (occupancy = 4,))" +samples = 1 +time = 0.001452235 +[[trials]] +config = "(tm = 128, tn = 256, tk = 32, hints = (occupancy = 4,))" +samples = 1 +time = 0.002287661 +[[trials]] +config = "(tm = 64, tn = 256, tk = 32, hints = (occupancy = 4,))" +samples = 1 +time = 0.000988892 +[[trials]] +config = "(tm = 256, tn = 256, tk = 32, hints = (occupancy = 4,))" +samples = 1 +time = 0.008887113 +[[trials]] +config = "(tm = 128, tn = 128, tk = 16, hints = (occupancy = 4,))" +samples = 1 +time = 0.001960091 +[[trials]] +config = "(tm = 64, tn = 128, tk = 16, hints = (occupancy = 4,))" +samples = 10 +time = 0.000322596 +[[trials]] +config = "(tm = 256, tn = 128, tk = 16, hints = (occupancy = 4,))" +samples = 1 +time = 0.004466961 +[[trials]] +config = "(tm = 128, tn = 64, tk = 16, hints = (occupancy = 4,))" +samples = 10 +time = 0.0003367525 +[[trials]] +config = "(tm = 64, tn = 64, tk = 16, hints = (occupancy = 4,))" +samples = 10 +time = 0.000337569 +[[trials]] +config = "(tm = 256, tn = 64, tk = 16, hints = (occupancy = 4,))" +samples = 1 +time = 0.002172467 +[[trials]] +config = "(tm = 128, tn = 256, tk = 16, hints = (occupancy = 4,))" +samples = 1 +time = 0.003208897 +[[trials]] +config = "(tm = 64, tn = 256, tk = 16, hints = (occupancy = 4,))" +samples = 1 +time = 0.001748267 +[[trials]] +config = "(tm = 256, tn = 256, tk = 16, hints = (occupancy = 4,))" +samples = 1 +time = 0.010046373 +[[trials]] +config = "(tm = 128, tn = 128, tk = 64, hints = (occupancy = 4,))" +samples = 3 +time = 0.000513938 +[[trials]] +config = "(tm = 64, tn = 128, tk = 64, hints = (occupancy = 4,))" +samples = 3 +time = 0.000404288 +[[trials]] +config = "(tm = 256, tn = 128, tk = 64, hints = (occupancy = 4,))" +samples = 1 +time = 0.000767991 +[[trials]] +config = "(tm = 128, tn = 64, tk = 64, hints = (occupancy = 4,))" +samples = 3 +time = 0.000494451 +[[trials]] +config = "(tm = 64, tn = 64, tk = 64, hints = (occupancy = 4,))" +samples = 3 +time = 0.0004683575 +[[trials]] +config = "(tm = 256, tn = 64, tk = 64, hints = (occupancy = 4,))" +samples = 3 +time = 0.000629924 +[[trials]] +config = "(tm = 128, tn = 256, tk = 64, hints = (occupancy = 4,))" +samples = 3 +time = 0.000603814 +[[trials]] +config = "(tm = 64, tn = 256, tk = 64, hints = (occupancy = 4,))" +samples = 3 +time = 0.000487308 +[[trials]] +config = "(tm = 256, tn = 256, tk = 64, hints = (occupancy = 4,))" +samples = 1 +time = 0.001319247 diff --git a/examples/tuning/8adec44285d153bd5eb3797ccfc7dfa916095679c257e09a871e799051cef845.NVIDIA_GeForce_RTX_5080.toml b/examples/tuning/8adec44285d153bd5eb3797ccfc7dfa916095679c257e09a871e799051cef845.NVIDIA_GeForce_RTX_5080.toml new file mode 100644 index 000000000..0885e32a9 --- /dev/null +++ b/examples/tuning/8adec44285d153bd5eb3797ccfc7dfa916095679c257e09a871e799051cef845.NVIDIA_GeForce_RTX_5080.toml @@ -0,0 +1,335 @@ +capability = "12.0.0" +config = "(tm = 128, tn = 128, tk = 64, occupancy = 2)" +cutile = "1.1.0" +date = "2026-12-02T19:05:51" +default_time = 0.000709241 +device = "NVIDIA GeForce RTX 5080" +index = 1 +kernels = "fused_gemm_kernel" +tileiras = "13.5.37" +time = 0.000709241 + +[[trials]] +config = "(tm = 128, tn = 128, tk = 64, occupancy = 2)" +samples = 10 +time = 0.000709241 +[[trials]] +config = "(tm = 64, tn = 128, tk = 64, occupancy = 2)" +samples = 10 +time = 0.000777007 +[[trials]] +config = "(tm = 256, tn = 128, tk = 64, occupancy = 2)" +samples = 3 +time = 0.001182593 +[[trials]] +config = "(tm = 128, tn = 64, tk = 64, occupancy = 2)" +samples = 10 +time = 0.000748484 +[[trials]] +config = "(tm = 64, tn = 64, tk = 64, occupancy = 2)" +samples = 10 +time = 0.00077269 +[[trials]] +config = "(tm = 256, tn = 64, tk = 64, occupancy = 2)" +samples = 10 +time = 0.000825698 +[[trials]] +config = "(tm = 128, tn = 256, tk = 64, occupancy = 2)" +samples = 3 +time = 0.00124003 +[[trials]] +config = "(tm = 64, tn = 256, tk = 64, occupancy = 2)" +samples = 10 +time = 0.000766868 +[[trials]] +config = "(tm = 256, tn = 256, tk = 64, occupancy = 2)" +samples = 1 +time = 0.005899158 +[[trials]] +config = "(tm = 128, tn = 128, tk = 32, occupancy = 2)" +samples = 10 +time = 0.000740249 +[[trials]] +config = "(tm = 64, tn = 128, tk = 32, occupancy = 2)" +samples = 10 +time = 0.000775845 +[[trials]] +config = "(tm = 256, tn = 128, tk = 32, occupancy = 2)" +samples = 1 +time = 0.002436648 +[[trials]] +config = "(tm = 128, tn = 64, tk = 32, occupancy = 2)" +samples = 10 +time = 0.000737063 +[[trials]] +config = "(tm = 64, tn = 64, tk = 32, occupancy = 2)" +samples = 3 +time = 0.000897832 +[[trials]] +config = "(tm = 256, tn = 64, tk = 32, occupancy = 2)" +samples = 10 +time = 0.000733015 +[[trials]] +config = "(tm = 128, tn = 256, tk = 32, occupancy = 2)" +samples = 1 +time = 0.002241255 +[[trials]] +config = "(tm = 64, tn = 256, tk = 32, occupancy = 2)" +samples = 10 +time = 0.000742723 +[[trials]] +config = "(tm = 256, tn = 256, tk = 32, occupancy = 2)" +samples = 1 +time = 0.008690888 +[[trials]] +config = "(tm = 128, tn = 128, tk = 16, occupancy = 2)" +samples = 10 +time = 0.000732163 +[[trials]] +config = "(tm = 64, tn = 128, tk = 16, occupancy = 2)" +samples = 10 +time = 0.000850935 +[[trials]] +config = "(tm = 256, tn = 128, tk = 16, occupancy = 2)" +samples = 1 +time = 0.003869226 +[[trials]] +config = "(tm = 128, tn = 64, tk = 16, occupancy = 2)" +samples = 10 +time = 0.000750488 +[[trials]] +config = "(tm = 64, tn = 64, tk = 16, occupancy = 2)" +samples = 3 +time = 0.000931115 +[[trials]] +config = "(tm = 256, tn = 64, tk = 16, occupancy = 2)" +samples = 10 +time = 0.000715683 +[[trials]] +config = "(tm = 128, tn = 256, tk = 16, occupancy = 2)" +samples = 1 +time = 0.003212985 +[[trials]] +config = "(tm = 64, tn = 256, tk = 16, occupancy = 2)" +samples = 10 +time = 0.000771968 +[[trials]] +config = "(tm = 256, tn = 256, tk = 16, occupancy = 2)" +samples = 1 +time = 0.012975138 +[[trials]] +config = "(tm = 128, tn = 128, tk = 64, occupancy = 1)" +samples = 10 +time = 0.000810129 +[[trials]] +config = "(tm = 64, tn = 128, tk = 64, occupancy = 1)" +samples = 10 +time = 0.000854682 +[[trials]] +config = "(tm = 256, tn = 128, tk = 64, occupancy = 1)" +samples = 3 +time = 0.001002808 +[[trials]] +config = "(tm = 128, tn = 64, tk = 64, occupancy = 1)" +samples = 3 +time = 0.000953246 +[[trials]] +config = "(tm = 64, tn = 64, tk = 64, occupancy = 1)" +samples = 3 +time = 0.001040508 +[[trials]] +config = "(tm = 256, tn = 64, tk = 64, occupancy = 1)" +samples = 3 +time = 0.000969355 +[[trials]] +config = "(tm = 128, tn = 256, tk = 64, occupancy = 1)" +samples = 3 +time = 0.001401781 +[[trials]] +config = "(tm = 64, tn = 256, tk = 64, occupancy = 1)" +samples = 3 +time = 0.000943478 +[[trials]] +config = "(tm = 256, tn = 256, tk = 64, occupancy = 1)" +samples = 1 +time = 0.002870667 +[[trials]] +config = "(tm = 128, tn = 128, tk = 32, occupancy = 1)" +samples = 10 +time = 0.000820158 +[[trials]] +config = "(tm = 64, tn = 128, tk = 32, occupancy = 1)" +samples = 3 +time = 0.000979094 +[[trials]] +config = "(tm = 256, tn = 128, tk = 32, occupancy = 1)" +samples = 10 +time = 0.000838101 +[[trials]] +config = "(tm = 128, tn = 64, tk = 32, occupancy = 1)" +samples = 3 +time = 0.000970588 +[[trials]] +config = "(tm = 64, tn = 64, tk = 32, occupancy = 1)" +samples = 3 +time = 0.001109036 +[[trials]] +config = "(tm = 256, tn = 64, tk = 32, occupancy = 1)" +samples = 3 +time = 0.000904435 +[[trials]] +config = "(tm = 128, tn = 256, tk = 32, occupancy = 1)" +samples = 1 +time = 0.001720965 +[[trials]] +config = "(tm = 64, tn = 256, tk = 32, occupancy = 1)" +samples = 3 +time = 0.000918852 +[[trials]] +config = "(tm = 256, tn = 256, tk = 32, occupancy = 1)" +samples = 1 +time = 0.003950368 +[[trials]] +config = "(tm = 128, tn = 128, tk = 16, occupancy = 1)" +samples = 10 +time = 0.000832892 +[[trials]] +config = "(tm = 64, tn = 128, tk = 16, occupancy = 1)" +samples = 3 +time = 0.001133651 +[[trials]] +config = "(tm = 256, tn = 128, tk = 16, occupancy = 1)" +samples = 10 +time = 0.00082692 +[[trials]] +config = "(tm = 128, tn = 64, tk = 16, occupancy = 1)" +samples = 3 +time = 0.001039436 +[[trials]] +config = "(tm = 64, tn = 64, tk = 16, occupancy = 1)" +samples = 3 +time = 0.001308868 +[[trials]] +config = "(tm = 256, tn = 64, tk = 16, occupancy = 1)" +samples = 3 +time = 0.000938037 +[[trials]] +config = "(tm = 128, tn = 256, tk = 16, occupancy = 1)" +samples = 1 +time = 0.002145196 +[[trials]] +config = "(tm = 64, tn = 256, tk = 16, occupancy = 1)" +samples = 3 +time = 0.000950601 +[[trials]] +config = "(tm = 256, tn = 256, tk = 16, occupancy = 1)" +samples = 1 +time = 0.00650165 +[[trials]] +config = "(tm = 128, tn = 128, tk = 64, occupancy = 4)" +samples = 1 +time = 0.002294945 +[[trials]] +config = "(tm = 64, tn = 128, tk = 64, occupancy = 4)" +samples = 3 +time = 0.000951702 +[[trials]] +config = "(tm = 256, tn = 128, tk = 64, occupancy = 4)" +samples = 1 +time = 0.009360185 +[[trials]] +config = "(tm = 128, tn = 64, tk = 64, occupancy = 4)" +samples = 3 +time = 0.001151104 +[[trials]] +config = "(tm = 64, tn = 64, tk = 64, occupancy = 4)" +samples = 3 +time = 0.00109511 +[[trials]] +config = "(tm = 256, tn = 64, tk = 64, occupancy = 4)" +samples = 1 +time = 0.006050661 +[[trials]] +config = "(tm = 128, tn = 256, tk = 64, occupancy = 4)" +samples = 1 +time = 0.005828015 +[[trials]] +config = "(tm = 64, tn = 256, tk = 64, occupancy = 4)" +samples = 1 +time = 0.001992852 +[[trials]] +config = "(tm = 256, tn = 256, tk = 64, occupancy = 4)" +samples = 1 +time = 0.015710293 +[[trials]] +config = "(tm = 128, tn = 128, tk = 32, occupancy = 4)" +samples = 1 +time = 0.002974881 +[[trials]] +config = "(tm = 64, tn = 128, tk = 32, occupancy = 4)" +samples = 10 +time = 0.000737353 +[[trials]] +config = "(tm = 256, tn = 128, tk = 32, occupancy = 4)" +samples = 1 +time = 0.009555909 +[[trials]] +config = "(tm = 128, tn = 64, tk = 32, occupancy = 4)" +samples = 3 +time = 0.000910456 +[[trials]] +config = "(tm = 64, tn = 64, tk = 32, occupancy = 4)" +samples = 10 +time = 0.00072996 +[[trials]] +config = "(tm = 256, tn = 64, tk = 32, occupancy = 4)" +samples = 1 +time = 0.005589721 +[[trials]] +config = "(tm = 128, tn = 256, tk = 32, occupancy = 4)" +samples = 1 +time = 0.00812293 +[[trials]] +config = "(tm = 64, tn = 256, tk = 32, occupancy = 4)" +samples = 1 +time = 0.00359688 +[[trials]] +config = "(tm = 256, tn = 256, tk = 32, occupancy = 4)" +samples = 1 +time = 0.023516443 +[[trials]] +config = "(tm = 128, tn = 128, tk = 16, occupancy = 4)" +samples = 1 +time = 0.007189391 +[[trials]] +config = "(tm = 64, tn = 128, tk = 16, occupancy = 4)" +samples = 1 +time = 0.002091085 +[[trials]] +config = "(tm = 256, tn = 128, tk = 16, occupancy = 4)" +samples = 1 +time = 0.017836844 +[[trials]] +config = "(tm = 128, tn = 64, tk = 16, occupancy = 4)" +samples = 10 +time = 0.000811302 +[[trials]] +config = "(tm = 64, tn = 64, tk = 16, occupancy = 4)" +samples = 3 +time = 0.000912359 +[[trials]] +config = "(tm = 256, tn = 64, tk = 16, occupancy = 4)" +samples = 1 +time = 0.007569239 +[[trials]] +config = "(tm = 128, tn = 256, tk = 16, occupancy = 4)" +samples = 1 +time = 0.017033107 +[[trials]] +config = "(tm = 64, tn = 256, tk = 16, occupancy = 4)" +samples = 1 +time = 0.005337132 +[[trials]] +config = "(tm = 256, tn = 256, tk = 16, occupancy = 4)" +samples = 1 +time = 0.031954801 diff --git a/examples/tuning/8f421ec601098b07b62208e1662b992b35dd1c8bad22d2ab1998d435e886db43.NVIDIA_GeForce_RTX_5080.toml b/examples/tuning/8f421ec601098b07b62208e1662b992b35dd1c8bad22d2ab1998d435e886db43.NVIDIA_GeForce_RTX_5080.toml new file mode 100644 index 000000000..a9fbd9d48 --- /dev/null +++ b/examples/tuning/8f421ec601098b07b62208e1662b992b35dd1c8bad22d2ab1998d435e886db43.NVIDIA_GeForce_RTX_5080.toml @@ -0,0 +1,59 @@ +capability = "12.0.0" +config = "(tile_n = 4096, hints = (occupancy = 2,))" +cutile = "1.1.0" +date = "2026-12-02T19:13:30" +default_time = 0.00018156075 +device = "NVIDIA GeForce RTX 5080" +index = 7 +kernels = "layer_norm_fwd" +tileiras = "13.5.37" +time = 0.0001608656 + +[[trials]] +config = "(tile_n = 4096, hints = NamedTuple())" +samples = 10 +time = 0.00018156075 +[[trials]] +config = "(tile_n = 1024, hints = NamedTuple())" +samples = 3 +time = 0.00024208433333333332 +[[trials]] +config = "(tile_n = 2048, hints = NamedTuple())" +samples = 10 +time = 0.00017945925 +[[trials]] +config = "(tile_n = 4096, hints = (occupancy = 1,))" +samples = 10 +time = 0.0001804902 +[[trials]] +config = "(tile_n = 1024, hints = (occupancy = 1,))" +samples = 3 +time = 0.00024198433333333334 +[[trials]] +config = "(tile_n = 2048, hints = (occupancy = 1,))" +samples = 10 +time = 0.00017857879999999999 +[[trials]] +config = "(tile_n = 4096, hints = (occupancy = 2,))" +samples = 10 +time = 0.0001608656 +[[trials]] +config = "(tile_n = 1024, hints = (occupancy = 2,))" +samples = 10 +time = 0.00017179400000000002 +[[trials]] +config = "(tile_n = 2048, hints = (occupancy = 2,))" +samples = 10 +time = 0.000159483 +[[trials]] +config = "(tile_n = 4096, hints = (occupancy = 4,))" +samples = 10 +time = 0.0001803258 +[[trials]] +config = "(tile_n = 1024, hints = (occupancy = 4,))" +samples = 10 +time = 0.0001604528 +[[trials]] +config = "(tile_n = 2048, hints = (occupancy = 4,))" +samples = 10 +time = 0.0001785746 diff --git a/examples/tuning/c9ca6b6eeac2a24ba5b0beb06b90d20884a62b078d4f454806cd02ddec3d0ffb.NVIDIA_GeForce_RTX_5080.toml b/examples/tuning/c9ca6b6eeac2a24ba5b0beb06b90d20884a62b078d4f454806cd02ddec3d0ffb.NVIDIA_GeForce_RTX_5080.toml new file mode 100644 index 000000000..967b74587 --- /dev/null +++ b/examples/tuning/c9ca6b6eeac2a24ba5b0beb06b90d20884a62b078d4f454806cd02ddec3d0ffb.NVIDIA_GeForce_RTX_5080.toml @@ -0,0 +1,59 @@ +capability = "12.0.0" +config = "(tile_m = 64, tile_n = 64, hints = NamedTuple())" +cutile = "1.1.0" +date = "2026-12-02T19:05:25" +default_time = 0.00018578933333333335 +device = "NVIDIA GeForce RTX 5080" +index = 1 +kernels = "fmha_kernel" +tileiras = "13.5.37" +time = 0.00018578933333333335 + +[[trials]] +config = "(tile_m = 64, tile_n = 64, hints = NamedTuple())" +samples = 10 +time = 0.00018578933333333335 +[[trials]] +config = "(tile_m = 128, tile_n = 64, hints = NamedTuple())" +samples = 10 +time = 0.00020273766666666668 +[[trials]] +config = "(tile_m = 64, tile_n = 128, hints = NamedTuple())" +samples = 10 +time = 0.00019193 +[[trials]] +config = "(tile_m = 128, tile_n = 128, hints = NamedTuple())" +samples = 1 +time = 0.0004254425 +[[trials]] +config = "(tile_m = 64, tile_n = 64, hints = (occupancy = 1,))" +samples = 3 +time = 0.00024005366666666667 +[[trials]] +config = "(tile_m = 128, tile_n = 64, hints = (occupancy = 1,))" +samples = 10 +time = 0.0002216755 +[[trials]] +config = "(tile_m = 64, tile_n = 128, hints = (occupancy = 1,))" +samples = 3 +time = 0.00023955966666666664 +[[trials]] +config = "(tile_m = 128, tile_n = 128, hints = (occupancy = 1,))" +samples = 3 +time = 0.0003718225 +[[trials]] +config = "(tile_m = 64, tile_n = 64, hints = (occupancy = 4,))" +samples = 10 +time = 0.000223937 +[[trials]] +config = "(tile_m = 128, tile_n = 64, hints = (occupancy = 4,))" +samples = 1 +time = 0.000607842 +[[trials]] +config = "(tile_m = 64, tile_n = 128, hints = (occupancy = 4,))" +samples = 3 +time = 0.00028042566666666664 +[[trials]] +config = "(tile_m = 128, tile_n = 128, hints = (occupancy = 4,))" +samples = 1 +time = 0.001982843 diff --git a/examples/tuning/e1d2525f0b2ecc0e6b5b11c8b9ac278a1eb32b2c2037106e1b7407cdacf11138.NVIDIA_GeForce_RTX_5080.toml b/examples/tuning/e1d2525f0b2ecc0e6b5b11c8b9ac278a1eb32b2c2037106e1b7407cdacf11138.NVIDIA_GeForce_RTX_5080.toml new file mode 100644 index 000000000..c42df2ac8 --- /dev/null +++ b/examples/tuning/e1d2525f0b2ecc0e6b5b11c8b9ac278a1eb32b2c2037106e1b7407cdacf11138.NVIDIA_GeForce_RTX_5080.toml @@ -0,0 +1,155 @@ +capability = "12.0.0" +config = "(tile_n = 64, tile_k = 64, hints = NamedTuple())" +cutile = "1.1.0" +date = "2026-12-02T19:13:23" +default_time = 0.0003535685 +device = "NVIDIA GeForce RTX 5080" +index = 2 +kernels = "fused_moe_kernel" +tileiras = "13.5.37" +time = 0.000345754 + +[[trials]] +config = "(tile_n = 128, tile_k = 64, hints = NamedTuple())" +samples = 10 +time = 0.0003535685 +[[trials]] +config = "(tile_n = 64, tile_k = 64, hints = NamedTuple())" +samples = 10 +time = 0.000345754 +[[trials]] +config = "(tile_n = 128, tile_k = 32, hints = NamedTuple())" +samples = 10 +time = 0.0003577015 +[[trials]] +config = "(tile_n = 64, tile_k = 32, hints = NamedTuple())" +samples = 10 +time = 0.0003471315 +[[trials]] +config = "(tile_n = 128, tile_k = 128, hints = NamedTuple())" +samples = 10 +time = 0.0004136955 +[[trials]] +config = "(tile_n = 64, tile_k = 128, hints = NamedTuple())" +samples = 3 +time = 0.0004371545 +[[trials]] +config = "(tile_n = 128, tile_k = 64, hints = (occupancy = 1,))" +samples = 3 +time = 0.000550806 +[[trials]] +config = "(tile_n = 64, tile_k = 64, hints = (occupancy = 1,))" +samples = 10 +time = 0.0003781395 +[[trials]] +config = "(tile_n = 128, tile_k = 32, hints = (occupancy = 1,))" +samples = 3 +time = 0.0004349305 +[[trials]] +config = "(tile_n = 64, tile_k = 32, hints = (occupancy = 1,))" +samples = 10 +time = 0.0004016785 +[[trials]] +config = "(tile_n = 128, tile_k = 128, hints = (occupancy = 1,))" +samples = 3 +time = 0.00057477 +[[trials]] +config = "(tile_n = 64, tile_k = 128, hints = (occupancy = 1,))" +samples = 3 +time = 0.000512224 +[[trials]] +config = "(tile_n = 128, tile_k = 64, hints = (occupancy = 2,))" +samples = 10 +time = 0.000353383 +[[trials]] +config = "(tile_n = 64, tile_k = 64, hints = (occupancy = 2,))" +samples = 10 +time = 0.0003459845 +[[trials]] +config = "(tile_n = 128, tile_k = 32, hints = (occupancy = 2,))" +samples = 10 +time = 0.000357957 +[[trials]] +config = "(tile_n = 64, tile_k = 32, hints = (occupancy = 2,))" +samples = 10 +time = 0.0003473475 +[[trials]] +config = "(tile_n = 128, tile_k = 128, hints = (occupancy = 2,))" +samples = 10 +time = 0.000413109 +[[trials]] +config = "(tile_n = 64, tile_k = 128, hints = (occupancy = 2,))" +samples = 3 +time = 0.000436017 +[[trials]] +config = "(tile_n = 128, tile_k = 64, hints = (occupancy = 4,))" +samples = 3 +time = 0.000548431 +[[trials]] +config = "(tile_n = 64, tile_k = 64, hints = (occupancy = 4,))" +samples = 10 +time = 0.0003781745 +[[trials]] +config = "(tile_n = 128, tile_k = 32, hints = (occupancy = 4,))" +samples = 1 +time = 0.001376254 +[[trials]] +config = "(tile_n = 64, tile_k = 32, hints = (occupancy = 4,))" +samples = 10 +time = 0.000367715 +[[trials]] +config = "(tile_n = 128, tile_k = 128, hints = (occupancy = 4,))" +samples = 3 +time = 0.000570563 +[[trials]] +config = "(tile_n = 64, tile_k = 128, hints = (occupancy = 4,))" +samples = 3 +time = 0.000507646 +[[trials]] +config = "(tile_n = 128, tile_k = 64, hints = (num_worker_warps = 8,))" +samples = 10 +time = 0.000408561 +[[trials]] +config = "(tile_n = 64, tile_k = 64, hints = (num_worker_warps = 8,))" +samples = 10 +time = 0.000363963 +[[trials]] +config = "(tile_n = 128, tile_k = 32, hints = (num_worker_warps = 8,))" +samples = 10 +time = 0.000369879 +[[trials]] +config = "(tile_n = 64, tile_k = 32, hints = (num_worker_warps = 8,))" +samples = 10 +time = 0.0003678855 +[[trials]] +config = "(tile_n = 128, tile_k = 128, hints = (num_worker_warps = 8,))" +samples = 10 +time = 0.0004301665 +[[trials]] +config = "(tile_n = 64, tile_k = 128, hints = (num_worker_warps = 8,))" +samples = 10 +time = 0.000395887 +[[trials]] +config = "(tile_n = 128, tile_k = 64, hints = (occupancy = 2, num_worker_warps = 8))" +samples = 10 +time = 0.000407539 +[[trials]] +config = "(tile_n = 64, tile_k = 64, hints = (occupancy = 2, num_worker_warps = 8))" +samples = 10 +time = 0.0003642685 +[[trials]] +config = "(tile_n = 128, tile_k = 32, hints = (occupancy = 2, num_worker_warps = 8))" +samples = 10 +time = 0.0003700745 +[[trials]] +config = "(tile_n = 64, tile_k = 32, hints = (occupancy = 2, num_worker_warps = 8))" +samples = 10 +time = 0.0003692525 +[[trials]] +config = "(tile_n = 128, tile_k = 128, hints = (occupancy = 2, num_worker_warps = 8))" +samples = 3 +time = 0.0004334225 +[[trials]] +config = "(tile_n = 64, tile_k = 128, hints = (occupancy = 2, num_worker_warps = 8))" +samples = 10 +time = 0.0003900815 diff --git a/src/cuTile.jl b/src/cuTile.jl index adbf8a537..b1d305dc4 100644 --- a/src/cuTile.jl +++ b/src/cuTile.jl @@ -8,6 +8,7 @@ using IRStructurizer: Block, ControlFlowOp, BlockArgument, import IRStructurizer: operands, replace_uses!, insert_before! using Base: compilerbarrier, donotdelete +using Base.ScopedValues: ScopedValue, with using Core: MethodInstance, CodeInfo, SSAValue, Argument, ReturnNode, PiNode, QuoteNode, GlobalRef using Core.Compiler @@ -20,6 +21,8 @@ using EnumX public BFloat16 import CompilerCaching +import Scratch +import TOML using CompilerCaching: CacheView, method_instance, match_method_instance, typeinf!, seeded, results, get_source @@ -94,10 +97,12 @@ include("tiled.jl") include("broadcast.jl") include("mapreduce.jl") include("launch.jl") +include("tuning.jl") public launch, cufunction, TileKernel, TileBackend, DefaultBackend, Tiled, ByTarget, @compiler_options, @fpmode, @., - tileiras_version, bytecode_version, versioninfo + tileiras_version, bytecode_version, versioninfo, + autotune, TuningResult, @tuned, tuned, tuning_store, clear_tuning! # World age captured at __init__ time. The compilation pipeline # (typeinf!, codegen, bytecode emission) is invoked in this world via diff --git a/src/launch.jl b/src/launch.jl index c5e5180ee..d0be38412 100644 --- a/src/launch.jl +++ b/src/launch.jl @@ -597,14 +597,15 @@ function assemble(bytecode::Vector{UInt8}, sm_arch::VersionNumber, opt_level::In end end -# The compiled form of one configuration of a kernel: its CUBIN, shared by every -# CUDA context and persisted with the inference result, and the session-local -# kernels linked from it. +# The compiled form of one configuration of a kernel: its CUBIN and digest (see +# `kernel_digest`), shared by every CUDA context and persisted with the inference +# result, and the session-local kernels linked from it. mutable struct TileCompilerResults cubin::Union{Nothing, Vector{UInt8}} + digest::Union{Nothing, Vector{UInt8}} # linear-scanned by context; usually holds a single entry kernels::Vector{Tuple{CuContext, Any}} - TileCompilerResults() = new(nothing, Tuple{CuContext, Any}[]) + TileCompilerResults() = new(nothing, nothing, Tuple{CuContext, Any}[]) end # The results of every job of a kernel, attached by CompilerCaching to the @@ -660,13 +661,30 @@ function compile_or_lookup(job::TileJob) # for: the hook may look up the job itself. GPUCompiler.run_compile_hook(job) return ensure_cubin!(res) do - compile_unhooked(job, ci) + compile_unhooked(job, ci), kernel_digest(job, ci) end end -# The results `res`, with the CUBIN `compile()` returns unless one is published -# already. Concurrent calls for the same results wait for the one compiling it, -# and compile it themselves if that fails. +""" + kernel_digest(job::TileJob, [ci]) -> Vector{UInt8} + +A hash of what `job` compiles to, which tuning records are keyed by: the Tile IR +bytecode, emitted without debug information, and the optimization level. The debug +information holds source paths and line numbers, which differ between installations +and change when unrelated lines are edited. +""" +function kernel_digest(job::TileJob, ci::Core.CodeInstance=infer(job)) + (; bytecode, opt_level) = emit_tile(job, ci; debuginfo=false) + return ObjCache.keyhash(KERNEL_DIGEST_SCHEMA, bytecode, opt_level) +end + +# Bump when the digest stops identifying the same code, e.g. when it covers more +# inputs; tuning records keyed by an earlier digest no longer match afterwards. +const KERNEL_DIGEST_SCHEMA = 1 + +# The results `res`, with the CUBIN and digest `compile()` returns unless they are +# published already. Concurrent calls for the same results wait for the one +# compiling them, and compile them themselves if that fails. function ensure_cubin!(compile, res::TileCompilerResults) Base.@lock job_results_lock begin while res.cubin === nothing @@ -684,12 +702,13 @@ end compiling[res] = compiled try unlock(job_results_lock) - cubin = try + cubin, digest = try compile() finally # an interrupt here would leave us without the lock, unable to wake waiters Base.disable_sigint(() -> lock(job_results_lock)) end + res.digest = digest res.cubin = cubin return res finally @@ -830,6 +849,15 @@ Base.@nospecializeinfer function cufunction_compile(@nospecialize(f), @nospecial return kernel end +# The digest of the code `k` launches, from its compilation results. Not kept on +# the kernel: a field more made every launch allocate more. +function kernel_digest(k::TileKernel{F, TT}) where {F, TT} + argtypes, const_argtypes = unwrap_argtypes(k.f, TT) + world = Base.get_world_counter() + job = tile_job(kernel_method_instance(k.f, argtypes, world), world; const_argtypes, k.opts...) + return compile_or_lookup(job).digest::Vector{UInt8} +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} = @@ -870,6 +898,14 @@ function flatten_params!(arg_exprs, type_exprs, @nospecialize(T), val_expr) return end +# Set while `autotune` compiles its candidates: a launch then selects and loads +# its kernel, but returns before running it. +const dry_run = ScopedValue(false) + +# Set by `tuned` to a vector that collects the kernel of every launch, dry runs +# included, to identify the code it launches. +const launch_observer = ScopedValue{Union{Nothing, Vector{TileKernel}}}(nothing) + # `convert=Val(...)` is the AbstractKernel callable convention from CUDACore; # `@cuda` passes `convert=Val(false)` because it converted the arguments # already. Arguments are always taken as converted, so direct `kernel(args...)` @@ -898,14 +934,13 @@ end # facts its `ArraySpec` records, such as alignment. tt = Tuple{args...} select = if tt == k.parameters[2] - :(same_labels(k.labels, labels) ? k.fun : variant_function(k, $tt, labels, $leaves)) + :(same_labels(k.labels, labels) ? k : variant(k, $tt, labels, $leaves)) else - :(variant_function(k, $tt, labels, $leaves)) + :(variant(k, $tt, labels, $leaves)) end quote labels = overlap_labels(args...) - fun = $select - state = KernelState() + kernel = $select grid_dims = blocks isa Integer ? (blocks,) : blocks for (i, dim) in enumerate(grid_dims) if dim > MAX_GRID_DIM @@ -913,9 +948,13 @@ end "Use multiple kernel launches for larger workloads.") end end + observed = launch_observer[] + observed === nothing || push!(observed, kernel) + dry_run[] && return nothing + 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{$(type_exprs...)}, $(arg_exprs...); + cudacall(kernel.fun, Tuple{$(type_exprs...)}, $(arg_exprs...); blocks=grid_dims, threads, kwargs...) return nothing end @@ -1078,12 +1117,12 @@ end return true end -# The function of `k` compiled for launch arguments of types `tt` whose arrays, -# at `leaves`, carry overlap `labels`. Compilation is cached, so this costs a -# cache lookup. -@noinline variant_function(k::TileKernel, @nospecialize(tt), labels::Tuple{Vararg{Int}}, - leaves) = - cufunction(k.f, tt; k.opts..., alias_groups=labels_to_groups(labels, leaves)).fun +# The kernel `k` compiled for launch arguments of types `tt` whose arrays, at +# `leaves`, carry overlap `labels`. Compilation is cached, so this costs a cache +# lookup. +@noinline variant(k::TileKernel, @nospecialize(tt), labels::Tuple{Vararg{Int}}, + leaves)::TileKernel = + cufunction(k.f, tt; k.opts..., alias_groups=labels_to_groups(labels, leaves)) # `@cuda` compiles from the converted arguments' types, so compile for their # overlap pattern here rather than for disjoint arrays and then a variant. diff --git a/src/tuning.jl b/src/tuning.jl new file mode 100644 index 000000000..136c3128d --- /dev/null +++ b/src/tuning.jl @@ -0,0 +1,656 @@ +#============================================================================= + Autotuning + + `autotune(f, space)` times a launch under every configuration of a search + space and returns the fastest. A configuration is a `NamedTuple` that `f` + interprets, so tile sizes, hints and grids are tuned the same way. +=============================================================================# + +# A sample covers at least this much time: for short kernels, one call is +# dominated by launch overhead and timer resolution. +const SAMPLE_TIME = 1e-3 + +struct TuningTrial + config::NamedTuple + time::Float64 + samples::Int + error::Union{Nothing, CapturedException} +end + +""" + TuningResult + +The outcome of [`autotune`](@ref). Its fields are + +- `best`: the chosen configuration; +- `trials`: one entry per configuration, in the order of the search space, each with + the fields `config`, `time` (the fastest time per call observed, in seconds, where + short calls are timed in batches; `Inf` for a configuration that failed), `samples` (how often it was timed) and `error` (a + `CapturedException` with the error it threw while being compiled, or `nothing`); +- `prepare_time` and `measure_time`: the wall time spent compiling the candidates and + timing them, in seconds. + +Displaying a `TuningResult` shows the trials ranked by time. +""" +struct TuningResult + best::NamedTuple + trials::Vector{TuningTrial} + prepare_time::Float64 + measure_time::Float64 +end + +""" + autotune(f, space; samples=10, tolerance=0.02, setup=nothing, search=true) -> TuningResult + +Find the fastest configuration of a launch by timing every configuration in `space`. +`f(config)` performs the launch, or several, for one configuration: + +```julia +result = ct.autotune((tm=(128, 64, 256), tn=(128, 64, 256), occupancy=(2, 1, 4))) do cfg + @cuda backend=cuTile blocks=cld(M, cfg.tm) * cld(N, cfg.tn) occupancy=cfg.occupancy matmul( + A, B, C, ct.Constant(cfg.tm), ct.Constant(cfg.tn), ct.Constant(32)) +end +result.best # (tm = 128, tn = 128, occupancy = 2), for instance +``` + +`space` is either a `NamedTuple` of collections, meaning every combination of their +values (with the first field varying fastest), or any collection of `NamedTuple`s with +the same field names, taken as is. A generator with a condition expresses constraints: +`((; tm, tn) for tm in (64, 128), tn in (64, 128) if tm >= tn)`. The first configuration +is the default: it wins ties. + +The search first compiles every configuration, concurrently, by calling `f` with +cuTile launches turned into no-ops that compile and load their kernel but do not run +it. A configuration whose launch throws is recorded with its error and left out; if +every configuration fails, `autotune` throws. Then it launches each remaining +configuration once more, untimed, and times them in turns, `samples` times each, +keeping each one's fastest time per call and dropping those that are far behind the +best (more than 2× after the first round, 1.25× after the third). Without `setup`, a +sample of a call that takes less than about a millisecond times a batch of calls. The result's `best` is the first configuration, in the order of +`space`, whose time is within a fraction `tolerance` of the fastest one, so that +measurement noise does not decide between configurations that perform alike. + +`f` is called many times, so it should only compute on the host and launch cuTile +kernels on the task's stream. Other GPU work in it, such as a `copyto!` or a CUDA.jl +kernel, also runs while the candidates are compiled. A launch overwrites its outputs +on every call: for a kernel that also reads what it writes, pass `setup(config)`, +which is called before every call after the compilation to restore the inputs, or +tune on scratch data. An error after the compilation, for instance from a kernel that +faults, is not caught, and neither is a CUDA error during it. + +`search` selects the search strategy. Only exhaustive search exists: `true` or +`:exhaustive`. +""" +function autotune(f, space; samples::Integer=10, tolerance::Real=0.02, setup=nothing, + search::Union{Bool, Symbol}=true) + search === true || search === :exhaustive || + throw(ArgumentError("unknown search strategy $(repr(search)); only `true` or `:exhaustive` are supported")) + samples >= 1 || throw(ArgumentError("samples must be at least 1, got $samples")) + tolerance >= 0 || throw(ArgumentError("tolerance must be nonnegative, got $tolerance")) + CUDACore.is_capturing() && + error("cannot autotune while capturing a CUDA graph, as that launches the kernels") + + configs = configurations(space) + n = length(configs) + + t0 = time_ns() + errors = prepare(f, configs) + prepare_time = (time_ns() - t0) / 1e9 + + alive = findall(isnothing, errors) + isempty(alive) && + error("all $n configurations failed; the first, $(first(configs)), with:\n" * + sprint(showerror, first(errors))) + + t0 = time_ns() + times, counts, alive = measure(f, configs, alive, samples, setup) + measure_time = (time_ns() - t0) / 1e9 + + best = choose(times, alive, tolerance) + trials = [TuningTrial(configs[i], times[i], counts[i], errors[i]) for i in 1:n] + return TuningResult(configs[best], trials, prepare_time, measure_time) +end + +# The configurations of a search space, in order. +function configurations(space::NamedTuple) + configs = vec([NamedTuple{keys(space)}(vals) for vals in Iterators.product(values(space)...)]) + isempty(configs) && throw(ArgumentError("the search space is empty")) + return configs +end +function configurations(space) + configs = collect(space) + isempty(configs) && throw(ArgumentError("the search space is empty")) + names = nothing + for config in configs + config isa NamedTuple || + throw(ArgumentError("a configuration must be a NamedTuple, got $(repr(config))")) + names = something(names, keys(config)) + keys(config) == names || + throw(ArgumentError("configurations $(configs[1]) and $config have different fields")) + end + return configs +end + +# Call `f` on every configuration with launches only compiling, in concurrent tasks +# (`tileiras` runs as a subprocess, so even a single thread compiles concurrently). +# Returns the error of each configuration, or `nothing`. A CUDA error is rarely +# specific to one configuration, as no kernel runs, and may leave the context +# unusable: it ends the search, like an interrupt. +function prepare(f, configs) + n = length(configs) + errors = Vector{Union{Nothing, CapturedException}}(nothing, n) + # New tasks start without CUDA state, i.e., on the default device. + ctx = CUDACore.context() + next = Threads.Atomic{Int}(1) + work() = try + CUDACore.context!(ctx) do + with(dry_run => true) do + while (i = Threads.atomic_add!(next, 1)) <= n + try + f(configs[i]) + catch err + (err isa InterruptException || err isa CUDACore.CuError) && rethrow() + errors[i] = CapturedException(err, catch_backtrace()) + end + end + end + end + catch + next[] = n + 1 + rethrow() + end + workers = [Threads.@spawn work() for _ in 1:min(n, max(1, Sys.CPU_THREADS ÷ 2))] + try + foreach(wait, workers) + finally + # After a failure, or an interrupt of the caller, let the workers finish the + # configurations they have started, but no others. + next[] = n + 1 + for worker in workers + try + wait(worker) + catch err + err isa TaskFailedException || rethrow() + end + end + end + return errors +end + +# Time the candidates `alive` (indices into `configs`), returning the fastest time +# per call and the number of samples of each, and the candidates that survived. +function measure(f, configs, alive, samples, setup) + function timed(i, evals) + setup === nothing || setup(configs[i]) + CUDACore.synchronize() + t0 = time_ns() + for _ in 1:evals + f(configs[i]) + end + CUDACore.synchronize() + return (time_ns() - t0) / 1e9 / evals + end + + evals = ones(Int, length(configs)) + for i in alive + # The first launch of a kernel can be slower, e.g. with lazy module loading. + timed(i, 1) + if setup === nothing + evals[i] = max(1, floor(Int, SAMPLE_TIME / timed(i, 1))) + end + end + return race(i -> timed(i, evals[i]), alive, length(configs), samples) +end + +# Sample the candidates `alive` in turns, `rounds` times, keeping the fastest time +# of each, and dropping the ones far behind the best after the first and third +# rounds. `sample(i)` times candidate `i` once. +function race(sample, alive, n, rounds) + times = fill(Inf, n) + counts = zeros(Int, n) + alive = collect(alive) + for round in 1:rounds + for i in alive + times[i] = min(times[i], sample(i)) + counts[i] += 1 + end + factor = round == 1 ? 2.0 : round == 3 ? 1.25 : nothing + if factor !== nothing + cutoff = factor * minimum(i -> times[i], alive) + filter!(i -> times[i] <= cutoff, alive) + end + end + return times, counts, alive +end + +# The first of the candidates `alive` within `tolerance` of the fastest of them. +function choose(times, alive, tolerance) + cutoff = (1.0 + tolerance) * minimum(i -> times[i], alive) + return minimum(i for i in alive if times[i] <= cutoff) +end + +function Base.show(io::IO, result::TuningResult) + print(io, "TuningResult(best=", result.best, ", ", length(result.trials), " trials)") +end + +function Base.show(io::IO, ::MIME"text/plain", result::TuningResult) + trials = result.trials + failed = count(trial -> trial.error !== nothing, trials) + print(io, "TuningResult: best of ", length(trials), " configurations is ", result.best) + failed > 0 && print(io, " (", failed, " failed)") + println(io) + print(io, "compiled in ", round(result.prepare_time; digits=1), " s, timed in ", + round(result.measure_time; digits=1), " s") + + fastest = minimum(trial -> trial.time, trials) + ranked = sort(trials; by=trial -> trial.time) + best = findfirst(trial -> trial.error === nothing && isequal(trial.config, result.best), ranked) + rows = map(enumerate(ranked)) do (rank, trial) + config = join(("$name = $(repr(value))" for (name, value) in pairs(trial.config)), ", ") + if trial.error === nothing + (string(round(trial.time * 1e3; sigdigits=4)), + string(round(trial.time / fastest; digits=2), "×"), string(trial.samples), + config, rank == best ? " ← best" : "") + else + ("failed", "", "", config, " " * error_summary(trial.error.ex)) + end + end + header = ("time (ms)", "", "samples", "configuration", "") + widths = [maximum(textwidth, (header[c], (row[c] for row in rows)...)) for c in 1:3] + for row in (header, rows...) + println(io) + print(io, " ", lpad(row[1], widths[1]), " ", lpad(row[2], widths[2]), " ", + lpad(row[3], widths[3]), " ", row[4], row[5]) + end +end + +# The message of `err` on one line, without the backtrace that some errors print. +function error_summary(err; limit=100) + message = first(split(sprint(showerror, err), "\nStacktrace:")) + message = join(split(message), ' ') + return length(message) > limit ? first(message, limit - 1) * "…" : message +end + + +#============================================================================= + Tuned call sites + + `tuned(f, space)` launches `f(config)` with the configuration a tuning record + names, or with the first one when there is none. Records are found by what the + first configuration launches, so they stop matching when the kernels change. +=============================================================================# + +""" + @tuned(f, [space]; axes..., key=(), search=false, setup=nothing, shipped=nothing) + +Call [`tuned`](@ref) with the arguments given, keeping tuning records per package. They +go to a scratch space of the package that contains the call (see +[`tuning_store`](@ref)), or, for a call outside a package, to the scratch space +`Scratch.@get_scratch!` would use there. Passing `store` overrides that. + +```julia +ct.@tuned(tm=(128, 64, 256), tn=(128, 64, 256), occupancy=(2, 1, 4)) do (; tm, tn, occupancy) + @cuda backend=cuTile blocks=cld(M, tm) * cld(N, tn) occupancy=occupancy matmul( + A, B, C, ct.Constant(tm), ct.Constant(tn), ct.Constant(32)) +end +``` +""" +macro tuned(args...) + keyword(arg, name) = (Meta.isexpr(arg, :(=)) || Meta.isexpr(arg, :kw)) && arg.args[1] === name + store_given = any(args) do arg + keyword(arg, :store) || Meta.isexpr(arg, :parameters) && + any(param -> param === :store || keyword(param, :store), arg.args) + end + # A call takes its `;` keywords first and `name=value` as `kw`, while a macro + # call with a `do` block puts the function first. + params = [arg for arg in args if Meta.isexpr(arg, :parameters)] + others = [Meta.isexpr(arg, :(=)) ? Expr(:kw, arg.args...) : arg + for arg in args if !Meta.isexpr(arg, :parameters)] + call = Expr(:call, GlobalRef(@__MODULE__, :tuned), params..., others...) + # before any splatted keywords, which then take precedence + store_given || push!(call.args, Expr(:kw, :store, __module__)) + return esc(call) +end + +""" + tuned(f, [space]; axes..., key=(), search=false, setup=nothing, store, shipped=nothing) + +Call `f(config)` once, with the configuration of the search space that a tuning record +names, or else with the first configuration, and return its value. Call sites normally +use [`@tuned`](@ref), which picks `store`. + +The space is given either as keyword arguments, each a collection of values for one +field of the configuration, meaning every combination of them as in +[`autotune`](@ref), or positionally as a collection of `NamedTuple`s. + +Records are found by content. Calling `f` with the first configuration while launches +only compile (as `autotune` does) shows which kernels it launches; the record of the call +site is the one for those kernels' code, the search space, `key` and the GPU's compute +capability. A record therefore stops applying when the kernels change, and the closure's +argument types count, including the layout of its arrays, without being declared. What +the record does not see, such as a problem size that does not change the kernel code, +can be added with `key`: `key=(nextpow(2, N),)` keeps separate records for sizes of +different magnitudes. `key` should consist of numbers, strings, symbols and tuples of +them, as their printed form is what is hashed. + +Without a record, `search=true` makes the call search the space with `autotune` first, +save the winner as a record, and launch it. With the default `search=false`, it launches +the first configuration. In the call that searches, `setup(config)` is called before +every launch of the search, and once more before the launch that the call performs, to +restore inputs that a kernel overwrites (see `autotune`). A call reached while another +`tuned` call identifies its launch or compiles its candidates does not search. + +Records live as one TOML file each in the directory `store`, or in the scratch space of +`store` when it is a `Module`, as `@tuned` passes it. `shipped` names a directory of +records consulted after `store`, such as one committed to a package's repository; it is +only read. Of the records for the same key, one from a GPU with the same name is +preferred. Records found are remembered for the session per call site: the type of `f` +(which includes the types of the values it captures), `key`, the space (compared by +value), the device, `store` and `shipped` (as given, so a relative path or the active +project that a `Module` store depends on should not change during a session). + +`f` is called more than once, so it must consist of host code without side effects and +cuTile launches on the task's stream, and which kernels it launches must not depend on +the results of earlier launches in the same call. A call that launches no cuTile kernel +is rejected. +""" +function tuned(f, space=nothing; key=(), search::Union{Bool, Symbol}=false, setup=nothing, + store::Union{Module, AbstractString}, shipped::Union{Nothing, AbstractString}=nothing, + axes...) + search === false || search === true || search === :exhaustive || + throw(ArgumentError("unknown search strategy $(repr(search)); only `false`, `true` or `:exhaustive` are supported")) + if space === nothing + isempty(axes) && throw(ArgumentError("no search space given")) + space = values(axes) + elseif !isempty(axes) + throw(ArgumentError("give the search space either positionally or as keyword arguments, not both")) + end + site = (key, space, CUDACore.device(), store, shipped) + choice = remembered(f, site) + if choice !== nothing && choice.world == Base.get_world_counter() && + (choice.recorded || search === false && choice.records == records_saved[]) + return f(choice.config) + end + return tune(f, site, search, setup) +end + +# The configuration chosen for a call site, and whether a record named it. +struct Choice{C} + config::C + recorded::Bool + # the world it was chosen in: redefinitions may change what the site launches + world::UInt + # for the first configuration, chosen for want of a record: how many records had + # been saved, as a later one may be for this site + records::Int +end + +# The number of records saved in this session. +const records_saved = Threads.Atomic{Int}(0) + +# The configurations chosen in this session, in a table per type of call site +# (closure and site key). Replaced rather than modified, so that a lookup +# takes no lock. +mutable struct Memo + Base.@atomic tables::IdDict{Type, Any} +end +const memo = Memo(IdDict{Type, Any}()) + +# The (inferred) type of the configurations of `space`. +config_type(::Type{S}) where {S} = eltype(Base.promote_op(configurations, S)) + +function remembered(f::F, site::S) where {F, S} + table = get(Base.@atomic(:acquire, memo.tables), Tuple{F, S}, nothing) + table isa Dict{S, Choice{config_type(fieldtype(S, 2))}} || return nothing + return get(table, site, nothing) +end + +function remember!(f::F, site::S, choice::Choice) where {F, S} + Base.@lock tuning_lock begin + tables = copy(Base.@atomic memo.tables) + table = get(tables, Tuple{F, S}, nothing) + T = Dict{S, Choice{config_type(fieldtype(S, 2))}} + table = table isa T ? copy(table) : T() + table[site] = choice + tables[Tuple{F, S}] = table + Base.@atomic :release memo.tables = tables + end +end + +# Guards the memo's updates, the records of `unsaved_records` and `searches`. +const tuning_lock = ReentrantLock() + +# The searches in progress, by record key, for others to wait for. +const searches = Dict{Vector{UInt8}, Threads.Condition}() + +# Records that could not be written, by the path they belong at. +const unsaved_records = Dict{String, Dict{String, Any}}() + +# Searches measure one at a time, so that their timings do not interfere. +const measure_lock = ReentrantLock() + +# Set while `tuned` searches. +const in_search = ScopedValue(false) + +@noinline function tune(f, site, search, setup) + key, space, dev, store, shipped = site + world = Base.get_world_counter() + # A site reached while another one identifies its launch or compiles its + # candidates would time launches that do nothing; one reached during another's + # search could wait for that search, which waits for it. + (dry_run[] || in_search[]) && (search = false) + configs = configurations(space) + record_key, observed = identify(f, configs, key, dev) + index, recorded, searched, records = find_or_search(f, configs, record_key, observed, search, + setup, store, shipped, dev) + recorded || @debug "No tuning record for a launch of $(kernel_label(observed)); using the first configuration" + choice = Choice{config_type(typeof(space))}(configs[index], recorded, world, records) + remember!(f, site, choice) + searched && setup !== nothing && setup(choice.config) + return f(choice.config) +end + +# The key of the record for calling `f` with configurations `configs`, from the +# kernels that `f` launches with the first of them, and those kernels. +function identify(f, configs, key, dev) + observed = TileKernel[] + with(dry_run => true, launch_observer => observed) do + f(first(configs)) + end + isempty(observed) && + throw(ArgumentError("the function passed to `tuned` launches no cuTile kernel")) + # with the types, which values of different types can print alike + space_id = join((repr(config) * "::" * string(typeof(config)) for config in configs), '\n') + record_key = ObjCache.keyhash(TUNING_RECORD_SCHEMA, map(kernel_digest, observed)..., + space_id, repr(key), string(CUDACore.capability(dev))) + return record_key, observed +end + +# Bump when records stop identifying the same launches; no earlier record matches +# afterwards. +const TUNING_RECORD_SCHEMA = 1 + +# The index of the configuration to use, whether a record named it, whether this +# call searched for it, and the number of records saved when it looked. One task +# searches per record key; the others wait for it, and search themselves if it +# fails. +function find_or_search(f, configs, record_key, observed, search, setup, store, shipped, dev) + lock(tuning_lock) + try + while true + index = find_record(configs, record_key, store, shipped, dev) + index === nothing || return index, true, false, records_saved[] + search === false && return 1, false, false, records_saved[] + searching = get(searches, record_key, nothing) + searching === nothing && break + wait(searching) + end + searching = Threads.Condition(tuning_lock) + searches[record_key] = searching + try + unlock(tuning_lock) + result = try + Base.@lock measure_lock with(in_search => true) do + autotune(f, configs; setup, search) + end + finally + # an interrupt here would leave us without the lock, unable to wake waiters + Base.disable_sigint(() -> lock(tuning_lock)) + end + index = findfirst(trial -> trial.config === result.best, result.trials) + save_record(store, record_key, dev, configs, index, result, observed) + return index, true, true, records_saved[] + finally + delete!(searches, record_key) + notify(searching) + end + finally + unlock(tuning_lock) + end +end + + +## the store + +""" + tuning_store(mod::Module) -> String + +The directory where [`@tuned`](@ref) calls in the package of `mod` keep their tuning +records: a scratch space of that package (see Scratch.jl), which goes away when the +package is removed. For a module outside a package, such as `Main`, it is the scratch +space that `Scratch.@get_scratch!` uses there: the active project's if that has a UUID, +and otherwise a global one. The directory is created when the first +record is saved. + +A package can ship records by copying files from this directory into its repository, +and passing that directory as `shipped` (see [`tuned`](@ref)). +""" +tuning_store(mod::Module) = Scratch.scratch_path(Scratch.find_uuid(mod), "tuning") + +store_path(store::Module) = tuning_store(store) +store_path(store::AbstractString) = store + +create_store(store::Module) = Scratch.get_scratch!(store, "tuning") +create_store(store::AbstractString) = mkpath(store) + +""" + clear_tuning!(store=Main) + +Delete the tuning records in `store`, a directory or a `Module` whose +[`tuning_store`](@ref) to use, and forget the configurations chosen in this session, so +that calls with `search=true` search again. +""" +function clear_tuning!(store::Union{Module, AbstractString}=Main) + dir = store_path(store) + Base.@lock tuning_lock begin + if isdir(dir) + for name in readdir(dir) + is_record_file(name) && rm(joinpath(dir, name); force=true) + end + end + filter!(((path, _),) -> dirname(path) != dir, unsaved_records) + Base.@atomic :release memo.tables = IdDict{Type, Any}() + end + return +end + +# Records are named after their key and the GPU they were made on, as more than one +# GPU can have the same compute capability. +record_name(record_key, dev) = + bytes2hex(record_key) * "." * replace(CUDACore.name(dev), r"[^A-Za-z0-9]+" => "_") * ".toml" +is_record_file(name) = occursin(r"^[0-9a-f]{64}\..*\.toml$", name) + +# The index of the configuration that a record for `record_key` names, preferring +# a record from the same GPU, then one in `store` over one in `shipped`. Creates +# nothing. Caller holds `tuning_lock`. +function find_record(configs, record_key, store, shipped, dev) + dirs = shipped === nothing ? (store_path(store),) : (store_path(store), shipped) + name = record_name(record_key, dev) + for dir in dirs + index = read_record(joinpath(dir, name), configs) + index === nothing || return index + end + prefix = bytes2hex(record_key) * "." + for dir in dirs + names = try + isdir(dir) ? readdir(dir) : String[] + catch err + err isa InterruptException && rethrow() + @debug "Cannot list tuning records in $dir" exception=err + String[] + end + for other in names + startswith(other, prefix) && other != name || continue + index = read_record(joinpath(dir, other), configs) + index === nothing || return index + end + end + return nothing +end + +# The index of the configuration the record at `path` names, if it exists and names +# one of `configs`. +function read_record(path, configs) + record = get(unsaved_records, path, nothing) + if record === nothing + record = try + isfile(path) || return nothing + TOML.parsefile(path) + catch err + err isa InterruptException && rethrow() + @debug "Ignoring tuning record $path, which cannot be read" exception=err + return nothing + end + end + index = get(record, "index", nothing) + if !(index isa Int64 && checkbounds(Bool, configs, index) && + get(record, "config", nothing) == repr(configs[index])) + @debug "Ignoring tuning record $path, which names no configuration of the search space" + return nothing + end + return Int(index) +end + +# Caller holds `tuning_lock`. +function save_record(store, record_key, dev, configs, index, result, observed) + trials = map(result.trials) do trial + entry = Dict{String, Any}("config" => repr(trial.config), "samples" => trial.samples) + isfinite(trial.time) && (entry["time"] = trial.time) + trial.error === nothing || (entry["error"] = error_summary(trial.error.ex)) + entry + end + record = Dict{String, Any}( + "config" => repr(configs[index]), + "index" => index, + "time" => result.trials[index].time, + "default_time" => result.trials[1].time, + "kernels" => kernel_label(observed), + "capability" => string(CUDACore.capability(dev)), + "device" => CUDACore.name(dev), + "date" => Libc.strftime("%Y-%m-%dT%H:%M:%S", time()), + "cutile" => string(pkgversion(@__MODULE__)), + "tileiras" => string(tileiras_version()), + "trials" => trials) + isfinite(record["default_time"]) || delete!(record, "default_time") + + path = joinpath(store_path(store), record_name(record_key, dev)) + temp = nothing + try + dir = create_store(store) + temp = tempname(dir; cleanup=false) + open(io -> TOML.print(io, record; sorted=true), temp, "w") + # replaces an earlier record at once, where `mv` would delete it first + Base.Filesystem.rename(temp, path) + catch err + err isa InterruptException && rethrow() + temp === nothing || try rm(temp; force=true) catch end + @warn "Cannot save tuning records in $(dirname(path)); keeping them for this session" exception=err maxlog=1 + unsaved_records[path] = record + end + Threads.atomic_add!(records_saved, 1) + return +end + +kernel_label(observed) = + join(unique(string(kernel.f isa Function ? nameof(kernel.f) : nameof(typeof(kernel.f))) + for kernel in observed), ", ") diff --git a/test/Project.toml b/test/Project.toml index ac4bb483e..67d0b4938 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -20,7 +20,7 @@ Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" cuTile = "0dea8319-8c4a-4662-a73d-20234d115b9a" [compat] -CUDA = "6.3" +CUDA = "6.6" FFTW = "1.10.0" FileCheck = "1.0" Microfloats = "0.2.6" diff --git a/test/codegen/reflection.jl b/test/codegen/reflection.jl index 11c7c5f73..d426c46bc 100644 --- a/test/codegen/reflection.jl +++ b/test/codegen/reflection.jl @@ -239,14 +239,14 @@ if ct.tileiras_available() put!(entered, nothing) take!(resume) end - return cubin + return cubin, UInt8[] end compiler = Threads.@spawn ct.ensure_cubin!(compile, res) bind(entered, compiler) take!(entered) waiters = try # other results compile meanwhile - other = Threads.@spawn ct.ensure_cubin!(() -> UInt8[2], ct.TileCompilerResults()) + other = Threads.@spawn ct.ensure_cubin!(() -> (UInt8[2], UInt8[]), ct.TileCompilerResults()) @test timedwait(() -> istaskdone(other), 60) === :ok && fetch(other).cubin == [2] # misses for the same results wait for the compilation in progress @@ -280,7 +280,7 @@ if ct.tileiras_available() take!(resume) error("injected compilation failure") end - return UInt8[1] + return UInt8[1], UInt8[] end compiler = Threads.@spawn ct.ensure_cubin!(compile, res) bind(entered, compiler) diff --git a/test/device/tuning.jl b/test/device/tuning.jl new file mode 100644 index 000000000..bc6b6f1de --- /dev/null +++ b/test/device/tuning.jl @@ -0,0 +1,619 @@ +using CUDA + +function tuning_copy(a::ct.TileArray{Float32,1}, b::ct.TileArray{Float32,1}, tile::Int) + bid = ct.bid(1) + ct.store(b; index=bid, tile=ct.load(a; index=bid, shape=(tile,))) + return +end + +function tuning_increment(a::ct.TileArray{Float32,1}, tile::Int) + bid = ct.bid(1) + ct.store(a; index=bid, tile=ct.load(a; index=bid, shape=(tile,)) .+ 1f0) + return +end + +const tuning_n = 2^16 +copy_launch(a, b, tile) = + @cuda backend=cuTile blocks=cld(tuning_n, tile) tuning_copy(a, b, ct.Constant(tile)) + +@testset "product space" begin + a = CUDA.rand(Float32, tuning_n) + b = CUDA.zeros(Float32, tuning_n) + space = (tile=(256, 1024), occupancy=(1, 2)) + result = ct.autotune(space) do cfg + @cuda backend=cuTile blocks=cld(tuning_n, cfg.tile) occupancy=cfg.occupancy tuning_copy( + a, b, ct.Constant(cfg.tile)) + end + @test [trial.config for trial in result.trials] == + [(tile=256, occupancy=1), (tile=1024, occupancy=1), + (tile=256, occupancy=2), (tile=1024, occupancy=2)] + @test result.best in [trial.config for trial in result.trials] + @test all(trial -> trial.error === nothing && isfinite(trial.time) && trial.samples >= 1, + result.trials) + @test Array(b) == Array(a) + @test occursin("best of 4 configurations", sprint(show, MIME"text/plain"(), result)) +end + +@testset "iterable space" begin + a = CUDA.rand(Float32, tuning_n) + b = CUDA.zeros(Float32, tuning_n) + space = ((; tile) for tile in (64, 128, 256, 512) if tile >= 128) + result = ct.autotune(cfg -> copy_launch(a, b, cfg.tile), space; samples=3, search=:exhaustive) + @test [trial.config.tile for trial in result.trials] == [128, 256, 512] + @test result.best.tile in (128, 256, 512) +end + +@testset "the default wins a tie" begin + a = CUDA.rand(Float32, tuning_n) + b = CUDA.zeros(Float32, tuning_n) + space = [(name=name, tile=1024) for name in (:a, :b, :c, :d)] + # identical launches, so any difference is noise + result = ct.autotune(cfg -> copy_launch(a, b, cfg.tile), space; tolerance=0.2) + @test result.best.name === :a +end + +@testset "failing candidates" begin + a = CUDA.rand(Float32, tuning_n) + b = CUDA.zeros(Float32, tuning_n) + result = ct.autotune((tile=(1024, 0),)) do cfg + cfg.tile == 0 && error("no such tile") + copy_launch(a, b, cfg.tile) + end + @test result.best == (tile=1024,) + failed = result.trials[2] + @test failed.error isa CapturedException + @test failed.error.ex == ErrorException("no such tile") + @test failed.samples == 0 && failed.time == Inf + @test occursin("no such tile", sprint(show, MIME"text/plain"(), result)) + + # a kernel that does not compile + result = ct.autotune(cfg -> copy_launch(a, b, cfg.tile), (tile=(1024, 1000),); samples=1) + @test result.best == (tile=1024,) + @test result.trials[2].error !== nothing + + @test_throws "all 2 configurations failed" ct.autotune(cfg -> error("never"), (tile=(1, 2),)) + + # a CUDA error may leave the context unusable, so it ends the search + @test_throws "ILLEGAL_ADDRESS" ct.autotune((tile=(1024, 256),)) do cfg + cfg.tile == 256 && throw(CuError(CUDA.ERROR_ILLEGAL_ADDRESS)) + copy_launch(a, b, cfg.tile) + end + # and no further candidates are started (more than there are workers) + n = Sys.CPU_THREADS + 16 + started = Threads.Atomic{Int}(0) + @test_throws "ILLEGAL_ADDRESS" ct.autotune((i=1:n,)) do cfg + Threads.atomic_add!(started, 1) + cfg.i == 2 && throw(CuError(CUDA.ERROR_ILLEGAL_ADDRESS)) + sleep(0.1) + end + @test started[] < n +end + +@testset "candidates compile in the caller's context" begin + ctx = CuContext(device()) + try + context!(ctx) do + a = CUDA.rand(Float32, tuning_n) + b = CUDA.zeros(Float32, tuning_n) + contexts = Channel{CuContext}(Inf) + result = ct.autotune((tile=(256, 1024),); samples=1) do cfg + put!(contexts, context()) + copy_launch(a, b, cfg.tile) + end + close(contexts) + @test all(==(ctx), contexts) + @test Array(b) == Array(a) + end + finally + CUDA.unsafe_destroy!(ctx) + end +end + +@testset "setup runs before every sample" begin + a = CUDA.zeros(Float32, tuning_n) + # the value each `setup` call finds, i.e. how often the kernel ran since the last one + seen = Float32[] + setup = cfg -> begin + push!(seen, only(unique(Array(a)))) + fill!(a, 0) + end + result = ct.autotune((tile=(256, 1024),); setup, samples=4) do cfg + @cuda backend=cuTile blocks=cld(tuning_n, cfg.tile) tuning_increment(a, ct.Constant(cfg.tile)) + end + # compiling the candidates launched nothing + @test first(seen) == 0 + @test all(==(1), seen[2:end]) + # each candidate is launched once untimed, then once per sample + @test length(seen) == sum(trial -> trial.samples + 1, result.trials) +end + +@testset "dry run" begin + a = CUDA.zeros(Float32, tuning_n) + launch() = @cuda backend=cuTile blocks=cld(tuning_n, 1024) tuning_increment(a, ct.Constant(1024)) + with(cuTile.dry_run => true) do + launch() + end + @test all(iszero, Array(a)) + launch() + @test all(==(1), Array(a)) + + # the grid is still checked + with(cuTile.dry_run => true) do + @test_throws "24-bit limit" @cuda backend=cuTile blocks=2^24 tuning_increment(a, ct.Constant(1024)) + end +end + +@testset "arguments" begin + @test_throws "unknown search strategy :random" ct.autotune(identity, (tile=(1,),); search=:random) + @test_throws ArgumentError ct.autotune(identity, (tile=(1,),); search=false) + @test_throws "samples must be at least 1" ct.autotune(identity, (tile=(1,),); samples=0) + @test_throws "tolerance must be nonnegative" ct.autotune(identity, (tile=(1,),); tolerance=-0.1) +end + +@testset "launches are observed" begin + a = CUDA.rand(Float32, tuning_n) + b = CUDA.zeros(Float32, tuning_n) + conv = ct.cuTileconvert + kernel = @cuda backend=cuTile launch=false tuning_copy(a, b, ct.Constant(1024)) + observed = ct.TileKernel[] + with(cuTile.launch_observer => observed, cuTile.dry_run => true) do + copy_launch(a, b, 1024) + kernel(conv(a), conv(b), conv(ct.Constant(1024)); blocks=cld(tuning_n, 1024)) + copy_launch(a, b, 256) + end + @test length(observed) == 3 + digests = map(ct.kernel_digest, observed) + @test digests[1] == digests[2] != digests[3] + @test all(iszero, Array(b)) +end + + +## tuned call sites + +# A launch of `tuning_copy`, as a call site does it. +copy_site(a, b; space=(tile=(1024, 256),), kwargs...) = + ct.tuned(cfg -> copy_launch(a, b, cfg.tile), space; kwargs...) + +# The record key of calling `f` on the configurations of `space`. +record_key(f, space; key=()) = first(cuTile.identify(f, cuTile.configurations(space), key, device())) + +@testset "without a record, the first configuration" begin + a = CUDA.rand(Float32, tuning_n) + b = CUDA.zeros(Float32, tuning_n) + store = mktempdir() + seen = [] + seen_lock = ReentrantLock() + site(search) = ct.tuned(; store, search, tile=(1024, 256)) do cfg + # candidates are compiled concurrently + Base.@lock seen_lock push!(seen, cfg) + copy_launch(a, b, cfg.tile) + end + # a dry run to identify the kernel, then the launch + site(false) + @test seen == [(tile=1024,), (tile=1024,)] + @test Array(b) == Array(a) + @test isempty(readdir(store)) + # then remembered + empty!(seen) + site(false) + @test seen == [(tile=1024,)] + + # searching is not prevented by having fallen back to the default + empty!(seen) + site(true) + @test length(seen) > 10 + @test length(readdir(store)) == 1 + record = cuTile.TOML.parsefile(joinpath(store, only(readdir(store)))) + @test record["config"] in ("(tile = 1024,)", "(tile = 256,)") + @test record["kernels"] == "tuning_copy" + @test record["device"] == CUDA.name(device()) + @test length(record["trials"]) == 2 + + # after which the record is used + empty!(seen) + site(true) + site(false) + @test length(seen) == 2 + + @test_throws "unknown search strategy :random" site(:random) +end + +@testset "the key identifies the code launched" begin + source = """ + import cuTile as ct + function tuning_kernel(a::ct.TileArray{T,1}, b::ct.TileArray{T,1}, tile::Int) where {T} + bid = ct.bid(1) + ct.store(b; index=bid, tile=ct.load(a; index=bid, shape=(tile,)) .* 2) + return + end + """ + copies = map([("/one/place/kernels.jl", ""), ("/another/place/kernels.jl", "# a comment\n\n")]) do (path, prefix) + mod = Module() + Base.include_string(mod, prefix * source, path) + Base.invokelatest(getglobal, mod, :tuning_kernel) + end + changed = let mod = Module() + Base.include_string(mod, replace(source, ".* 2" => ".* 3"), "/one/place/kernels.jl") + Base.invokelatest(getglobal, mod, :tuning_kernel) + end + launch(kernel, a, b) = cfg -> @cuda backend=cuTile blocks=cld(length(b), cfg.tile) kernel( + a, b, ct.Constant(cfg.tile)) + + a = CUDA.rand(Float32, tuning_n + 1) + b = CUDA.zeros(Float32, tuning_n) + space = (tile=(1024, 256),) + key = record_key(launch(copies[1], a, b), space) + @test record_key(launch(copies[2], a, b), space) == key + @test record_key(launch(changed, a, b), space) != key + @test record_key(launch(copies[1], a, b), (tile=(256, 1024),)) != key + @test record_key(launch(copies[1], a, b), space; key=(1,)) != key + @test record_key(launch(copies[1], Float16.(a), Float16.(b)), space) != key + @test record_key(launch(copies[1], view(a, 2:tuning_n + 1), b), space) != key + + # every kernel launched counts, in order and as often as it is launched + first_kernel = launch(copies[1], a, b) + second_kernel = cfg -> copy_launch(a, b, cfg.tile) + keys = [record_key(f, space) for f in (first_kernel, second_kernel, + cfg -> (first_kernel(cfg); second_kernel(cfg)), + cfg -> (second_kernel(cfg); first_kernel(cfg)), + cfg -> (first_kernel(cfg); first_kernel(cfg)))] + @test allunique(keys) + + # configurations that print alike, but have different types + @test record_key(second_kernel, [(tile=1024,), (tile=Int32(256),)]) != + record_key(second_kernel, [(tile=1024,), (tile=256,)]) + + # including a kernel compiled before + kernel = @cuda backend=cuTile launch=false copies[1](a, b, ct.Constant(1024)) + conv = ct.cuTileconvert + prebuilt = cfg -> kernel(conv(a), conv(b), conv(ct.Constant(1024)); blocks=cld(tuning_n, 1024)) + @test record_key(prebuilt, (tile=(1024,),)) == record_key(launch(copies[1], a, b), (tile=(1024,),)) + + @test_throws "launches no cuTile kernel" ct.tuned(cfg -> nothing; store=mktempdir(), tile=(1,)) +end + +@testset "the session memo" begin + a = CUDA.rand(Float32, tuning_n) + b = CUDA.zeros(Float32, tuning_n) + store = mktempdir() + # the same closure type, with spaces of the same type + seen = [] + site(space) = ct.tuned(cfg -> (push!(seen, cfg); copy_launch(a, b, cfg.tile)), space; store) + site((tile=(1024, 512),)) + site((tile=(256, 128),)) + site((tile=(1024, 512),)) + @test unique(seen) == [(tile=1024,), (tile=256,)] + + # a redefinition makes it look again + empty!(seen) + site((tile=(1024, 512),)) + @eval tuning_redefined() = nothing + site((tile=(1024, 512),)) + @test length(seen) == 3 + + # and so does a record saved meanwhile, which might be for this site + empty!(seen) + ct.tuned(cfg -> copy_launch(a, b, cfg.tile), (tile=(1024, 512),); store, search=true) + site((tile=(1024, 512),)) + @test length(seen) == 2 + + # the shipped records count + shipped = [mktempdir(), mktempdir()] + space = (tile=(1024, 512, 256),) + key = record_key(cfg -> copy_launch(a, b, cfg.tile), space) + for (dir, (config, index)) in zip(shipped, (("(tile = 512,)", 2), ("(tile = 256,)", 3))) + write(joinpath(dir, cuTile.record_name(key, device())), + "config = \"$config\"\nindex = $(repr(index))\n") + end + empty!(seen) + store = mktempdir() + for dir in shipped + ct.tuned(cfg -> (push!(seen, cfg); copy_launch(a, b, cfg.tile)), space; store, shipped=dir) + end + @test seen[[2, 4]] == [(tile=512,), (tile=256,)] +end + +@testset "nested call sites" begin + a = CUDA.rand(Float32, tuning_n) + b = CUDA.zeros(Float32, tuning_n) + inner_store = mktempdir() + # whether each launch of the inner site's search was a dry run + dry = Bool[] + ct.tuned(; store=mktempdir(), tile=(1024, 256)) do cfg + ct.tuned(inner -> copy_launch(a, b, inner.tile), (tile=(256, 1024),); + store=inner_store, search=true, setup=inner -> push!(dry, cuTile.dry_run[])) + end + # it searched when the outer site launched, not while that was identified + @test length(readdir(inner_store)) == 1 + @test !isempty(dry) && !any(dry) + + # nor while the outer site searches, even for the same record, which would mean + # waiting for its own search + space = (tile=(1024, 256),) + inner_searches = Ref(0) + outer = Threads.@spawn ct.tuned(space; store=mktempdir(), search=true) do cfg + ct.tuned(inner -> copy_launch(a, b, inner.tile), space; store=mktempdir(), search=true, + setup=inner -> inner_searches[] += 1) + end + @test timedwait(() -> istaskdone(outer), 120) === :ok + istaskdone(outer) && wait(outer) + # the outer site's final launch is the first outside its search + @test inner_searches[] > 0 +end + +@testset "keys separate records" begin + a = CUDA.rand(Float32, tuning_n) + b = CUDA.zeros(Float32, tuning_n) + store = mktempdir() + copy_site(a, b; store, search=true, key=(1,)) + copy_site(a, b; store, search=true, key=(2,)) + @test length(readdir(store)) == 2 +end + +@testset "setup before the launch" begin + a = CUDA.zeros(Float32, tuning_n) + resets = Ref(0) + setup = cfg -> (resets[] += 1; fill!(a, 0)) + site() = ct.tuned(; store=mktempdir(), search=true, setup, tile=(256, 1024)) do cfg + @cuda backend=cuTile blocks=cld(tuning_n, cfg.tile) tuning_increment(a, ct.Constant(cfg.tile)) + end + site() + # every launch but the last was undone + @test all(==(1), Array(a)) + @test resets[] > 2 +end + +@testset "searching while capturing a graph" begin + a = CUDA.rand(Float32, tuning_n) + b = CUDA.zeros(Float32, tuning_n) + store = mktempdir() + copy_site(a, b; store) + @test_throws "capturing" CUDA.capture() do + copy_site(a, b; store, search=true) + end + @test isempty(readdir(store)) +end + +@testset "records" begin + a = CUDA.rand(Float32, tuning_n) + b = CUDA.zeros(Float32, tuning_n) + space = (tile=(1024, 512, 256),) + key = record_key(cfg -> copy_launch(a, b, cfg.tile), space) + name = cuTile.record_name(key, device()) + write_record(dir, config, index; file=name) = + write(joinpath(mkpath(dir), file), "config = \"$config\"\nindex = $(repr(index))\n") + # which configuration the site launches, from the store, the shipped records, or neither + function used(store, shipped) + cuTile.clear_tuning!(mktempdir()) + seen = [] + ct.tuned(cfg -> (push!(seen, cfg); copy_launch(a, b, cfg.tile)), space; store, shipped) + return last(seen).tile + end + + store, shipped = mktempdir(), mktempdir() + write_record(shipped, "(tile = 512,)", 2) + @test used(store, shipped) == 512 + write_record(store, "(tile = 256,)", 3) + @test used(store, shipped) == 256 + + # a record from another GPU of the same compute capability, unless there is one + # from the same + store, shipped = mktempdir(), mktempdir() + other = replace(name, r"\..*\.toml$" => ".Another_GPU.toml") + write_record(store, "(tile = 256,)", 3; file=other) + @test used(store, shipped) == 256 + write_record(shipped, "(tile = 512,)", 2) + @test used(store, shipped) == 512 + + # records that name no configuration of the space + for (config, index) in (("(tile = 128,)", 2), ("(tile = 512,)", 4), ("(tile = 512,)", 1), + ("(tile = 512,)", true), ("(tile = 512,)", "2")) + store = mktempdir() + write_record(store, config, index) + @test used(store, nothing) == 1024 + end + store = mktempdir() + write(joinpath(store, name), "not toml = = =") + @test used(store, nothing) == 1024 +end + +@testset "an unwritable store" begin + a = CUDA.rand(Float32, tuning_n) + b = CUDA.zeros(Float32, tuning_n) + store = joinpath(tempname(), "store") + touch(dirname(store)) # a file, so the store cannot be created + @test_logs (:warn, r"Cannot save tuning records") match_mode=:any copy_site(a, b; store, search=true) + # another site with the same kernels and space finds the record in memory + seen = Ref(0) + ct.tuned(cfg -> (seen[] += 1; copy_launch(a, b, cfg.tile)), (tile=(1024, 256),); store, search=true) + @test seen[] == 2 +end + +@testset "concurrent searches" begin + a = CUDA.rand(Float32, tuning_n) + b = CUDA.zeros(Float32, tuning_n) + store = mktempdir() + # candidates compiled, i.e. dry runs off the tasks that call the site + compiled = Threads.Atomic{Int}(0) + entered, resume = Channel{Nothing}(1), Channel{Nothing}(1) + setups = Threads.Atomic{Int}(0) + # the first sample of the search waits until resumed + function setup(cfg) + if Threads.atomic_add!(setups, 1) == 0 + put!(entered, nothing) + take!(resume) + end + end + site() = ct.tuned(; store, search=true, setup, tile=(1024, 256)) do cfg + cuTile.dry_run[] && !haskey(task_local_storage(), :caller) && + Threads.atomic_add!(compiled, 1) + copy_launch(a, b, cfg.tile) + end + call() = task_local_storage(site, :caller, true) + searcher = Threads.@spawn call() + bind(entered, searcher) + take!(entered) + waiters = try + waiters = [Threads.@spawn(call()) for _ in 1:3] + searching = Base.@lock cuTile.tuning_lock only(values(cuTile.searches)) + @test timedwait(60) do + Base.@lock cuTile.tuning_lock length(searching.waitq) == 3 + end === :ok + waiters + finally + put!(resume, nothing) + end + tasks = [searcher; waiters] + finished = timedwait(() -> all(istaskdone, tasks), 60) === :ok + @test finished + finished && foreach(wait, tasks) + @test length(readdir(store)) == 1 + # one search + @test compiled[] == 2 + @test isempty(cuTile.searches) +end + +@testset "@tuned" begin + a = CUDA.rand(Float32, tuning_n) + b = CUDA.zeros(Float32, tuning_n) + launch = cfg -> copy_launch(a, b, cfg.tile) + space = (tile=(1024, 256),) + + # outside a package, records go to the global scratch space, as with `@get_scratch!` + @test ct.tuning_store(@__MODULE__) == ct.tuning_store(Main) == + cuTile.Scratch.scratch_dir("00000000-0000-0000-0000-000000000000", "tuning") + @test ct.tuning_store(cuTile) == + cuTile.Scratch.scratch_dir(string(Base.PkgId(cuTile).uuid), "tuning") + mktempdir() do dir + cuTile.Scratch.with_scratch_directory(dir) do + search = true + ct.@tuned(search=search, tile=(1024, 256)) do cfg + copy_launch(a, b, cfg.tile) + end + @test length(readdir(ct.tuning_store(Main))) == 1 + @test startswith(ct.tuning_store(Main), dir) + end + end + + # the call forms + store = mktempdir() + seen = [] + search = false + kwargs = (; store, search) + record = cfg -> (push!(seen, cfg); launch(cfg)) + configs = [(tile=1024,), (tile=256,)] + ct.@tuned(record; store, tile=(1024, 256)) + ct.@tuned(record, configs; store) + ct.@tuned(record, configs, store=store) + ct.@tuned(configs; store, search) do cfg + record(cfg) + end + ct.@tuned(configs, store=store, search=false) do cfg + record(cfg) + end + ct.@tuned(; kwargs..., tile=(1024, 256)) do cfg + record(cfg) + end + ct.@tuned(tile=(1024, 256); kwargs...) do (; tile) + record((; tile)) + end + @test length(seen) == 13 && all(==((tile=1024,)), seen) + @test isempty(readdir(store)) + + @test_throws "no search space" ct.@tuned(launch) + @test_throws "either positionally or as keyword arguments" ct.@tuned(launch, configs; tile=(1,)) +end + +# A package whose kernel is compiled into its package image, and which tunes its launch. +const tuned_package = """ + module TunedKernels + + using CUDA, cuTile, PrecompileTools + import cuTile as ct + + function copy_kernel(a, b, tile) + bid = ct.bid(1) + ct.store(b; index=bid, tile=ct.load(a; index=bid, shape=(tile,))) + return + end + + tuned_copy!(b, a; search=false) = ct.@tuned(search=search, tile=(1024, 256)) do cfg + @cuda backend=cuTile blocks=cld(length(a), cfg.tile) copy_kernel(a, b, ct.Constant(cfg.tile)) + end + + @setup_workload begin + a = CUDA.rand(Float32, $tuning_n); b = similar(a) + @compile_workload begin + @cuda backend=cuTile blocks=cld(length(a), 1024) copy_kernel(a, b, ct.Constant(1024)) + end + end + + end + """ + +const tuned_package_uuid = "4f5a3a1c-6a76-4d3e-9a9f-6f1d2b1b6c01" + +const tuned_package_prelude = quote + using CUDA, cuTile, Test, TunedKernels + import cuTile as ct + a = CUDA.rand(Float32, $tuning_n) + b = CUDA.zeros(Float32, $tuning_n) + # the launches of a call, through the observer that `tuned` uses + function launches(f) + observed = ct.TileKernel[] + Base.ScopedValues.with(f, cuTile.launch_observer => observed) + return observed + end +end + +function run_tuned_package(code, dir) + script = joinpath(dir, "script.jl") + write(script, string(tuned_package_prelude, "\n", code)) + project = dirname(Base.active_project()) + cmd = `$(Base.julia_cmd()) --startup-file=no --project=$project $script` + # a depot of its own for the package's image and scratch space, in front of ours + env = ("JULIA_DEPOT_PATH" => join([joinpath(dir, "depot"); DEPOT_PATH], ":"), + # the package's dependencies are found in environments up to its own + "JULIA_LOAD_PATH" => join([project, joinpath(dir, "packages"), "@stdlib"], ":")) + out = IOBuffer() + ok = success(pipeline(ignorestatus(addenv(cmd, env...)); stdout=out, stderr=out)) + ok || println(stderr, "--- child output ---\n", String(take!(out)), "\n--- end ---") + return ok +end + +@testset "a package's records" begin + mktempdir() do dir + pkg = joinpath(dir, "packages", "TunedKernels") + mkpath(joinpath(pkg, "src")) + write(joinpath(pkg, "src", "TunedKernels.jl"), tuned_package) + write(joinpath(pkg, "Project.toml"), """ + name = "TunedKernels" + uuid = "$tuned_package_uuid" + + [deps] + CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" + PrecompileTools = "aea7be01-6a6a-4083-8856-8a6e6704d82a" + cuTile = "0dea8319-8c4a-4662-a73d-20234d115b9a" + """) + + # the kernel from the package image is observed with its digest, and a search + # saves its record in the package's scratch space + @test run_tuned_package(quote + conv = ct.cuTileconvert + tt = Tuple{map(Core.Typeof, (conv(a), conv(b), conv(ct.Constant(1024))))...} + results = ct.cached_results(ct.tile_job(TunedKernels.copy_kernel, tt)) + @test results.cubin !== nothing && results.digest !== nothing + @test ct.kernel_digest(only(launches(() -> TunedKernels.tuned_copy!(b, a)))) == results.digest + + @test length(launches(() -> TunedKernels.tuned_copy!(b, a; search=true))) > 2 + @test ct.tuning_store(TunedKernels) == + joinpath($dir, "depot", "scratchspaces", $tuned_package_uuid, "tuning") + @test length(readdir(ct.tuning_store(TunedKernels))) == 1 + end, dir) + + # another session finds the record + @test run_tuned_package(quote + @test length(launches(() -> TunedKernels.tuned_copy!(b, a; search=true))) == 1 + end, dir) + end +end diff --git a/test/host/tuning.jl b/test/host/tuning.jl new file mode 100644 index 000000000..6b1d2dabd --- /dev/null +++ b/test/host/tuning.jl @@ -0,0 +1,61 @@ +@testset "search spaces" begin + # a product varies its first field fastest + @test cuTile.configurations((a=(1, 2), b=(:x, :y, :z))) == + [(a=1, b=:x), (a=2, b=:x), (a=1, b=:y), (a=2, b=:y), (a=1, b=:z), (a=2, b=:z)] + @test cuTile.configurations((a=[1, 2],)) == [(a=1,), (a=2,)] + + # other collections are taken as is + @test cuTile.configurations(((; a, b) for a in 1:3, b in 1:3 if a > b)) == + [(a=2, b=1), (a=3, b=1), (a=3, b=2)] + @test cuTile.configurations([(a=2,), (a=1,), (a=2,)]) == [(a=2,), (a=1,), (a=2,)] + + @test_throws "empty" cuTile.configurations((a=(), b=(1, 2))) + @test_throws "empty" cuTile.configurations(NamedTuple[]) + @test_throws "different fields" cuTile.configurations([(a=1,), (b=1,)]) + @test_throws "different fields" cuTile.configurations([(a=1, b=1), (b=1, a=1)]) + @test_throws "must be a NamedTuple" cuTile.configurations([(a=1,), 2]) +end + +@testset "racing and choosing" begin + # synthetic times: candidate i always takes times[i] + times = [1.0, 1.01, 1.2, 1.5, 3.0] + best, counts, alive = cuTile.race(i -> times[i], 1:5, 5, 10) + @test best == times + # more than 2× behind after the first round, more than 1.25× after the third + @test counts == [10, 10, 10, 3, 1] + @test alive == [1, 2, 3] + + # the earliest candidate within the tolerance of the fastest + @test cuTile.choose([1.01, 1.0, 1.5], [1, 2, 3], 0.02) == 1 + @test cuTile.choose([1.01, 1.0, 1.5], [1, 2, 3], 0.0) == 2 + @test cuTile.choose([1.0, 1.0], [1, 2], 0.0) == 1 + @test cuTile.choose([0.5, 1.0, 1.01], [2, 3], 0.02) == 2 + + # the minimum of noisy samples + samples = Dict(1 => [3.0, 1.0, 2.0], 2 => [2.0, 2.0, 2.0]) + best, counts, alive = cuTile.race(i -> popfirst!(samples[i]), [1, 2], 2, 3) + @test best == [1.0, 2.0] +end + +@testset "display" begin + trials = [cuTile.TuningTrial((tm=64, occupancy=1), 2e-3, 10, nothing), + cuTile.TuningTrial((tm=128, occupancy=1), 1e-3, 10, nothing), + cuTile.TuningTrial((tm=256, occupancy=1), Inf, 0, + CapturedException(ErrorException("out of registers"), []))] + result = cuTile.TuningResult(trials[2].config, trials, 1.5, 0.25) + shown = sprint(show, MIME"text/plain"(), result) + @test occursin("best of 3 configurations is (tm = 128, occupancy = 1) (1 failed)", shown) + lines = split(shown, '\n') + # ranked by time, failures last + @test occursin("tm = 128, occupancy = 1 ← best", lines[4]) + @test occursin("2.0×", lines[5]) + @test occursin("failed", lines[6]) && occursin("out of registers", lines[6]) + @test sprint(show, result) == "TuningResult(best=(tm = 128, occupancy = 1), 3 trials)" + + # the winner is marked once, on its fastest row, even when the space repeats it + trials = [cuTile.TuningTrial((x=missing,), 3e-3, 1, nothing), + cuTile.TuningTrial((x=missing,), 1e-3, 10, nothing)] + shown = sprint(show, MIME"text/plain"(), cuTile.TuningResult((x=missing,), trials, 0.0, 0.0)) + @test count("← best", shown) == 1 + @test occursin("1.0× 10 x = missing ← best", shown) +end