CUDA Tile Programming (TileContext)
TornadoVM can compile a task through NVIDIA CUDA Tile instead of the SIMT path. A tile kernel describes what one tile block does over tiles of a tensor, and the tile compiler decides how many threads back it, which tensor-core instruction to issue, and how tiles move through shared memory. Nothing in the API names a thread, a warp or a fragment.
This path is CUDA-only and additive: a tile task shares a TaskGraph, a stream and its device
buffers with ordinary JIT tasks and with native library tasks.
Requirements
CUDA Toolkit |
13.3 or newer for the CUDA Tile C++ surface. A userspace install is enough:
|
Driver |
R580 or newer to load a CUDA 13 cubin. |
GPU |
Compute capability 8.0 or newer. |
Below any of these, a tile task fails with TornadoDeviceTileNotSupported naming the missing
requirement, and the unit tests report [UNSUPPORTED] rather than failing.
TileContext in one example
A task is a tile task when its kernel method takes a TileContext as its first parameter, in the
same way a leading KernelContext selects the kernel-parallel API.
public static void gemm(TileContext tc, HalfFloatArray a, HalfFloatArray b, FloatArray c,
int m, int n, int k) {
PartitionView av = tc.partition(tc.view(a, m, k), 64, 32);
PartitionView bv = tc.partition(tc.view(b, k, n), 32, 64);
PartitionView cv = tc.partition(tc.view(c, m, n), 64, 64);
Tile acc = tc.zeros(DType.F32, 64, 64);
for (int step = 0; step < k / 32; step++) {
acc = tc.mma(av.load(tc.bidX(), step), bv.load(step, tc.bidY()), acc);
}
cv.store(acc, tc.bidX(), tc.bidY());
}
// The worker grid counts TILE BLOCKS, not threads.
WorkerGrid2D worker = new WorkerGrid2D(M / 64, N / 64);
GridScheduler grid = new GridScheduler("s0.gemm", worker);
TaskGraph graph = new TaskGraph("s0")
.transferToDevice(DataTransferMode.EVERY_EXECUTION, a, b)
.task("gemm", Gemm::gemm, new TileContext(), a, b, c, M, N, K)
.transferToHost(DataTransferMode.EVERY_EXECUTION, c);
try (TornadoExecutionPlan plan = new TornadoExecutionPlan(graph.snapshot())) {
plan.withGridScheduler(grid).execute();
}
Three rules
Tile shapes are compile-time constants and powers of two. A shape is part of the kernel’s type, so a differently shaped variant is a differently compiled kernel. Passing a shape as a method parameter is rejected at sketch time with a message naming the argument. Write a literal or a
static final int, and note that a constant passed into a helper does not count, because inlining happens after parsing.Extents are not constrained. Views take runtime extents, so the problem size does not specialise the kernel; only the tile shape does.
The worker grid counts tile blocks and the block is pinned to
1x1x1byCUDATileScheduler. Do not set local work yourself.
API reference
Every operation below is a real method on TileContext or PartitionView, and every one has
a JVM implementation as well as a lowering, so a tile kernel also runs as ordinary Java.
That dual life is worth knowing when a test passes unexpectedly. If a tile kernel fails to
compile and tornado.recover.bailout is enabled, the task quietly runs the JVM implementation
on the host and produces the right answer, so nothing fails. That option is off by default,
and tornado-test sets -Dtornado.recover.bailout=False explicitly as well; if you turn it
back on, confirm with --printKernel that a kernel was generated at all.
Block indices
Java |
CUDA Tile C++ |
Notes |
|---|---|---|
|
|
index of this tile block |
|
|
grid size; what a persistent kernel strides by |
setBlockIndex and setBlockCount exist for the JVM path only - they let a plain Java caller
place a kernel invocation when running it as ordinary code, and have no device meaning.
Views, partitions and memory
Java |
CUDA Tile C++ |
Notes |
|---|---|---|
|
|
1, 2 or 3 extents; extents may be runtime values |
|
|
a row pitch and a starting offset instead of a contiguous view; extents and stride stay runtime values. See Interleaved layouts below |
|
|
a raw |
|
|
the same buffer as plain signed bytes |
|
|
fp8 only: the format ( |
|
|
1, 2 or 3 tile extents, each a power-of-two constant |
|
|
rank 1, 2 or 3; caller guarantees in bounds |
|
|
zero-pads a partial tile |
|
|
rank 1, 2 or 3 |
|
|
writes only the in-bounds elements |
|
|
the read and write halves of an atomic protocol, as opposed to a plain load or store |
|
|
rank 1 and 2; relaxed order, device scope. Element types are CUDA Tile’s rule and are checked at compile time: add/sub take F16/F32/F64/S32, exchange excludes fp16, and min/max/and/or/xor are integer only. See Atomic accumulation |
The buffer types a view accepts, and the element type each maps to, are listed under Element types below.
Creating tiles
Java |
CUDA Tile C++ |
Notes |
|---|---|---|
|
|
rank 1 or 2 |
|
|
rank 1 or 2 |
|
|
the fill value must be a compile-time constant: it is emitted into the source |
|
|
0, 1, 2, … in row-major order. The rank-2 forms |
Elementwise arithmetic
Java |
CUDA Tile C++ |
Notes |
|---|---|---|
|
|
broadcasting: a dimension of extent 1 stretches |
|
|
two operands, elementwise - not reductions |
|
|
no named function in CUDA Tile. |
|
|
elementwise, unlike |
Comparisons, masks and select
Java |
CUDA Tile C++ |
Notes |
|---|---|---|
|
|
each takes |
|
|
combines two predicate tiles; non-predicate operands are rejected at compile time |
|
|
a prefix operator, not a named function |
|
|
produce predicate tiles, so they feed |
|
|
reduce a predicate tile to a predicate tile |
|
|
the only consumer of a predicate tile |
The scalar form is not a convenience. A mask usually compares against a runtime extent or block
offset, and the tile-to-tile form would need a full(...) whose fill value has to fold.
Math
Java |
CUDA Tile C++ |
Notes |
|---|---|---|
|
|
|
|
|
elementwise, shape preserved |
|
|
two operands, elementwise. |
|
|
integer tiles only - the builtins take |
|
|
integer tiles |
Reductions
Java |
CUDA Tile C++ |
Notes |
|---|---|---|
|
|
rank-2 tiles, axis 0 or 1 |
|
|
note the spelling: |
|
|
a product leaves the range of a narrow element type quickly; |
|
|
integer tiles only. Useful for collapsing a packed mask or a set of flags along an axis without unpacking it first |
A reduction keeps the reduced dimension, so the result broadcasts back against the tile it came
from. It cannot be stored into the view it came from, though: a 32x1 tile against a
32x32 partition view is refused by CUDA Tile’s same_shape constraint. Reduce, use the
result, and store a tile of the view’s own shape.
Scans
Java |
CUDA Tile C++ |
Notes |
|---|---|---|
|
|
inclusive prefix sum along the axis; the result has the tile’s own shape, unlike a reduction |
|
|
inclusive prefix product; the same range caveat as |
A scan is shape preserving, so unlike a reduction its result can be stored straight back into the partition view it was loaded from. That is what makes running offsets - a segment layout, a ragged row start, a cumulative distribution to sample from - expressible without a second pass.
Matrix multiply
Java |
CUDA Tile C++ |
Notes |
|---|---|---|
|
|
|
|
|
|
Shape and type
Java |
CUDA Tile C++ |
Notes |
|---|---|---|
|
|
stretches dimensions of extent 1; rank 1 or 2 |
|
|
same element count, row-major; rank 1, 2 or 3, and the only way to change rank |
|
|
a sub-tile, indexed in sub-tile units like a view addresses blocks; rank 1 or 2 |
|
|
rank 2 |
|
|
joins two tiles along one axis; the other dimension must match |
|
|
reinterprets the bits without converting; same width only |
|
|
any scalar pair, narrowing included. There is no |
Control flow
Java |
CUDA Tile C++ |
Notes |
|---|---|---|
a counted |
|
write an ordinary loop; no iterator API, which would allocate |
|
|
per-element conditions are |
Query methods
Tile exposes getDType, getRank, getDimension and getElement (JVM path only, for
tests and host debugging); TensorView exposes getDType, getRank, getExtent,
and getElementOffset/getRowStride for a strided view;
PartitionView adds getTileDimension and getBlockCount.
Rank support at a glance
Rank coverage is deliberately uneven: rank 3 exists for addressing, and arithmetic stays rank 2.
Ranks |
Operations |
|---|---|
1, 2, 3 |
|
1, 2 |
|
2 only |
|
any |
the elementwise operations, the comparisons, |
Launch hints
-Dtornado.cuda.tile.hints=occupancy=2,num_cta_in_cga=1 puts a
[[ using cutile : hint(0, ...) ]] attribute on every generated tile kernel. The keys are
CUDA Tile’s own; hint(0, ...) applies to all architectures.
The hint reaches the tile compiler and changes its resource decisions. Measured on sm_89 for the
FP16 GEMM of demos/22 at n = 1024:
Hint |
Registers / shared |
Kernel time |
|---|---|---|
none (compiler’s choice) |
110 / 36 KB |
65.3 us |
|
110 / 36 KB |
63.2 us (-2.9%, reproducible over three runs) |
|
125 / 20 KB |
132.5 us (2.0x slower) |
|
64 / 8 KB |
459.5 us (7.0x slower) |
Nothing derives hints automatically, and this is why. The compiler’s default is already close to the best of these, and forcing occupancy up costs 2x to 7x: a heuristic that maximised occupancy would be actively harmful at this shape. Deriving hints from the shapes a JIT knows is still the most promising thing this integration could do that a hand-written kernel cannot, but it needs a model of the tradeoff rather than a rule of thumb.
One caveat, verified against 13.3.73: hint keys are not validated. An invented key and an absurd value both compile silently and do nothing, so a hint that appears to have no effect may simply not exist.
The occupancy hint only acts on a straight-line k-loop; on a rolled loop the hinted and plain
kernels compile identically (see the next section).
K-loop unrolling
After task specialisation the k-loop of a tile GEMM has a constant trip count, so it can be either
kept as a loop or fully unrolled into straight-line load/load/mma steps. Which form is faster
depends on the architecture and the tile shape. Measured with FP16 GEMMs at n = 1024 to
4096:
GPU |
128x128x64 tiles |
Smaller tiles (32x32x32, 64x64x64, 128x128x32) |
|---|---|---|
A10 (sm_86), RTX 4090 (sm_89) |
straight-line 1.5x to 2.4x faster |
rolled 1.7x to 6.5x faster |
RTX 5070 Ti (sm_120) |
rolled 2.4x to 5.1x faster |
rolled 2.5x to 15x faster; some straight-line builds exceed the 120 s compile timeout |
By default the CUDA backend unrolls the k-loop only for 128x128x64 tiles on compute capability
8.x, and keeps it rolled everywhere else. -Dtornado.cuda.tile.unrollKLoop overrides that
choice:
auto(default): the per-architecture choice above.true: unroll every tile k-loop that fits the unroll budget.false: keep every tile k-loop rolled.
The property is read when a task is compiled, so it can be set for one compilation only, the
same way as tornado.cuda.tile.hints.
Rank
view and partition take one, two or three extents. Rank 3 is for addressing: a batch or
head dimension becomes a block index instead of arithmetic folded into the row index.
Arithmetic stays rank 2 - mma, the reductions and transpose are rank-2 operations - so a
rank-3 load is reshaped before it is used:
PartitionView aView = tc.partition(tc.view(a, batch, m, k), 1, TILE, TILE);
Tile left = tc.reshape(aView.load(batchIndex, rowBlock, step), TILE, TILE);
acc = tc.mma(left, right, acc);
That is the same shape as NVIDIA’s own kernels, which load a rank-4 tile from a [B, H, S, D]
view and reshape it before the first multiply.
View extents may be runtime values; tile extents may not, because a tile shape is part of the
kernel’s type. So tc.view(in, batch, rows, WIDTH) is fine with batch and rows as
parameters, while the WIDTH passed to partition has to be a literal or a
static final int.
Interleaved layouts
viewStrided gives a view a row pitch and a starting offset, so an interleaved format can be
read in place rather than being split into separate arrays first.
The case this exists for is a GGUF Q4_0 block: [fp16 scale][16 nibble bytes], 18 bytes,
repeated. That is a record with fields of two different widths, so reading it means viewing the
same allocation twice, once per field type. A ByteArray is an untyped buffer, so the view
takes the element type as an argument:
// scales: one fp16 per 18 bytes, i.e. every ninth half. Offsets and strides are in units
// of the element type, so this pitch is 9 halves and the nibble pitch below is 18 bytes.
PartitionView scaleView = tc.partition(
tc.viewStrided(raw, DType.F16, 0, blocks, 1, 9), BLOCKS, 1);
// nibbles: 16 usable bytes of every 18, starting at byte 2, out of the same buffer
PartitionView nibbleView = tc.partition(
tc.viewStrided(raw, DType.S8, 2, blocks, 16, 18), BLOCKS, 16);
Both lower to a ct::tensor_span carrying a ct::layout_strided_mapping whose extents and
strides are dynamic, which is the form a JIT emits, over a reinterpret_cast of the one
pointer — exactly what a hand-written CUDA Tile kernel does for the same record:
auto tview_2 = ct::partition_view{ct::tensor_span{(reinterpret_cast<__half *>(ul_0 + 16) + 0), ...
auto tview_3 = ct::partition_view{ct::tensor_span{(reinterpret_cast<signed char *>(ul_0 + 16) + 2), ...
Nothing in the API knows what the record means: the unpacking is ordinary tile arithmetic over
the two views — mask to the byte’s width (an S8 read sign-extends), shift out the high field,
concat the two halves, then centre and scale. TestTileRawBuffers does exactly that and
checks every decoded value; TestTileStridedViews covers the same layout split across two
typed arrays, which also still works.
Note that a strided view is not marked assume_aligned: its rows are not 16-byte aligned
in general, and telling the tile compiler otherwise would be a lie it would act on. A contiguous
view still carries the hint.
Atomic accumulation
view.atomicAdd(tile, blockIndices...) accumulates a tile into the view so that every
concurrent tile block’s contribution survives. It is what lets a split-K matmul finish in one
kernel instead of writing per-split partials and reducing them in a second pass.
CUDA Tile has no atomic read-modify-write on a partition_view: the view offers only
atomic_load and atomic_store, while ct::atomic_add takes a tile of pointers. The
code generator therefore computes that pointer tile from the view’s base pointer and extents.
Rank 2 needs the row and column index within the tile separately, and neither / nor % is
defined on a tile, so the indices come from two iota tiles broadcast to the tile shape.
The order is memory_order_relaxed and the scope is thread_scope_device: an accumulator
in device memory needs each element’s update to be atomic, not ordered against the others.
Observed lowering on sm_89: ATOMG.E.ADD.F32.FTZ.RN.STRONG.GPU - device scope matters, since
the default system scope emits the more expensive .SYS form.
Element types
DType names F16, BF16, F32, F64, TF32, FP8_E4M3, FP8_E5M2,
S8, S32 and the comparison-only PRED. Buffers that can be viewed:
FloatArray, HalfFloatArray, BFloat16Array, IntArray, Int8Array,
DoubleArray and FP8Array (whose view takes the format as an argument).
FP8 elementwise arithmetic, math functions, reductions and scans compute in F32:
CUDA Tile C++ provides no direct arithmetic overloads for FP8 tiles. Each operation converts
its result back to the original FP8 format, preserving the API’s tile type and rounding at
each operation boundary, not only when stored. Reductions and scans use FP32 intermediates
and convert their final outputs to FP8. To retain FP32 results across several operations,
explicitly cast the input tile to F32 first. scale still converts its scalar to the
tile’s element type before multiplication. Loads, stores, casts and shape operations keep
their existing types; mma and matmul retain their existing accumulation rules.
An mma validates its operand and accumulator pair against the CUDA Tile mmaf/mmai
tables, where the accumulator type must equal the result type. Observed lowerings on Ada
(sm_89): fp16 operands with an fp32 accumulator give HMMA.16816.F32, int8 operands with an
int32 accumulator give IMMA.16832.S8.S8.SAT, and fp64 gives scalar DADD/DMUL
because Ada has no fp64 tensor core.
Mixing tile tasks with everything else
A tile kernel is an ordinary module launch on the execution plan’s stream, so it composes without any extra synchronisation:
TaskGraph graph = new TaskGraph("chain")
.transferToDevice(DataTransferMode.EVERY_EXECUTION, input, matrix)
.task("scale", Chain::scale, input, scaled, 3.0f) // JIT SIMT
.task("tile", Chain::tileDouble, new TileContext(), scaled, doubled, N) // CUDA Tile
.libraryTask("gemv", CuBlas::cublasSgemv, /* ... */) // native cuBLAS
.task("bias", Chain::bias, projected, result, 0.25f) // JIT SIMT
.transferToHost(DataTransferMode.EVERY_EXECUTION, result);
The intermediates never leave the device. withCUDAGraph() captures the whole pipeline into one
CUDA graph, tile task included, and withIntraPlanConcurrency() works as usual.
Known limitations
Measured against the __tile_builtin__ set of CUDA 13.3 (84 operations, excluding the
assume_* hints and the tag-enumerator helpers), this API covers 71 of them. The
remaining 13 are: the ten _masked atomic variants whose unmasked forms exist;
atomic_compare_exchange in both forms; and permute, which needs a dimension_map
argument and only becomes meaningful above rank 2. Note that CUDA Tile’s Python DSL is a
larger surface again - it adds autotuning, device-side printing, static metaprogramming,
gather/scatter and block-scaled matmul, none of which appear among the C++ builtins - so
coverage against C++ is the narrower claim of the two.
The table above is the covered surface. What CUDA Tile has and this API does not, in rough order of how much it costs:
Missing |
Consequence |
|---|---|
|
|
fp8 tiles below compute capability 9.0 |
|
fp64 tensor cores |
an fp64 |
|
|
rank 4 and above, and rank 3 for some operations |
|
masked atomics and |
the eight unmasked read-modify-write atomics exist, as do the view’s |
|
on a rank-2 tile the only non-identity permutation is |
|
|
rounding and NaN-propagation modes |
CUDA Tile takes per-operation rounding tags; the generated code uses the defaults. |
Beyond the operation set:
Batch processing (
withBatch) is rejected for tile tasks.Tile intrinsics are not yet handled in
TornadoCUDAIntrinsicsReplacements, so a reflectively resolved tile kernel fails with an explanation instead of miscompiling.An
@Reducetask cannot share aTaskGraphwith a tile task: the reduction rewrite renames the graph, so aGridSchedulerkeyed on the original task id stops matching and the tile task silently runs as one block. Usetc.suminside the tile instead.TMA does not appear in the generated SASS on Ada (sm_89) because TMA is a Hopper unit; the alignment hint only pays off on sm_90 and newer.
Launch hints can be set but are not derived. See Launch hints above.
Examples
tornado-examples carries seven runnable tile examples. Each rewrites a known algorithm with
TileContext beside thread-level versions of the same thing, checks every result against a
sequential Java reference, and prints a table of times:
# smallest useful tile kernel
tornado -m tornado.examples/uk.ac.manchester.tornado.examples.tile.TileVectorAdd
# matrix multiply: @Parallel, KernelContext shared-memory tiles, TileContext
tornado -m tornado.examples/uk.ac.manchester.tornado.examples.tile.TileMatrixMultiply 512 20
# row softmax: the reductions and the broadcast back across the row
tornado -m tornado.examples/uk.ac.manchester.tornado.examples.tile.TileSoftmax 4096 50
# attention: thread-per-query against fused flash attention
tornado -m tornado.examples/uk.ac.manchester.tornado.examples.tile.TileAttention 1024 1024 20
# a transformer block built twice: all JIT, then JIT + CUDA Tile + cuBLAS
tornado -m tornado.examples/uk.ac.manchester.tornado.examples.tile.TileTransformerBlock
# a Q4_0 quantised projection, dequantised inside the tile kernel
tornado -m tornado.examples/uk.ac.manchester.tornado.examples.tile.TileQuantizedProjection 1024 1024 2048 20
# three Qwen3 kernels from jitllm#150, thread-level against tiles
tornado -m tornado.examples/uk.ac.manchester.tornado.examples.tile.TileQwenNormKernels 4096 50
The times are wall clock and include JVM-side dispatch, which dominates at small sizes; the
examples say so, and TileExamples carries the nsys recipe for kernel time alone.
Three kernels carry their own --printKernel output in a javadoc comment, next to the Java
they came from, so the lowering can be read without running anything:
TestTileRowKernels#softmaxRow (reductions, and how a reduced dimension broadcasts back inside
an operator), TestTileOpLevel#opMatmulHalf (matmul beside mma, and where the result
type comes from in each), and TestTileRecurrence#gatedDeltaRule (a loop-carried tile, which
is the case that becomes a named ct::tile variable at function scope instead of an auto).
Verifying and profiling
# the generated CUDA Tile C++ (expect ct:: calls and no inline PTX)
tornado --printKernel -m tornado.examples/...TileVectorAdd
tornado-test --printKernel -V uk.ac.manchester.tornado.unittests.tile.TestTileRowKernels
# tensor cores in the cached cubin
cuobjdump -sass $TORNADOVM_HOME/var/cuda-codecache/device-0-0/<kernel>-*.cubin | grep HMMA
# the unit tests, by area:
# Elementwise Matmul Chaining the core API and mixing with other task kinds
# RowKernels LlmKernels softmax, norms, activations, RoPE, dropout
# Attention AttentionVariants flash attention, GQA, split-KV decode, sinks, soft-cap
# GemmVariants Masking persistent and transposed GEMM; causal and ragged masks
# DTypes Atomics Shapes Rank3 int8/fp64/fp8, the atomic family, broadcast/reshape/extract
# MathOps StridedViews the math and bitwise surface; interleaved layouts
# RawBuffers one ByteArray viewed at two element types
# MixedPipelines Recurrence tile + KernelContext + cuBLAS in one graph; a
# loop-carried state tile (TileGym's gated delta rule)
# OpLevel one case per operator in isolation, plus the
# type-generic operators at F16, BF16 and FP8_E4M3
#
# OpLevel is the one to run first after a toolkit or driver change: every other suite tests a
# kernel, so a single operator's regression surfaces as a wrong number somewhere downstream,
# whereas here a failure names the operator and nothing else.
tornado-test -V uk.ac.manchester.tornado.unittests.tile.TestTileMatmul
tornado-test -V uk.ac.manchester.tornado.unittests.tile.TestTileAttention
tornado-test -V uk.ac.manchester.tornado.unittests.tile.TestTileMasking
Profiling
Profile the JVM directly rather than the launcher. nsys profile $(which tornado) ... produces a
report with no GPU rows, because the launcher execs a child JVM that the injection does not
follow. Build a Java @argfile from tornado --printJavaFlags and profile that instead. Two
details are required, or java @argfile fails immediately:
drop the leading
javabinary, or it is taken as the main class;inline the nested
@.../exportLists/...files, because Java does not expand an@argfilerecursively and passes the reference through as a literal argument.
tornado --printJavaFlags > flags.raw
python3 - flags.raw > tornadovm.args <<'EOF'
import sys
out = []
for token in open(sys.argv[1]).read().split():
if token.endswith("/bin/java"):
continue
if token.startswith("@"): # Java will not expand this itself
out.extend(open(token[1:]).read().split())
continue
out.append(token)
if "-m" in out: # drop a trailing -m <module/Main>
out = out[:out.index("-m")]
print("\n".join(out))
EOF
nsys profile --trace=cuda,nvtx --cuda-graph-trace=node -o tilechain \
java @tornadovm.args \
-m tornado.unittests/uk.ac.manchester.tornado.unittests.tile.TileChainBenchmark 2000
nsys stats --report cuda_gpu_kern_sum --report cuda_gpu_mem_time_sum tilechain.nsys-rep
TileChainBenchmark also reports CUDA Graph capture against plain execution for the mixed
pipeline, and verifies the result against a CPU reference afterwards, so a timing run doubles as a
correctness check. Application arguments go after the main class, not in the argfile.