Skip to content

nvidia TileIR backend - #9733

Draft
abadams wants to merge 64 commits into
mainfrom
abadams/tile_ir
Draft

abadams wants to merge 64 commits into
mainfrom
abadams/tile_ir

Conversation

@abadams

@abadams abadams commented Nov 30, 2026

Copy link
Copy Markdown
Member

This is a prototype cuda backend that passes tile IR kernels to the driver instead of PTX. It gets the same matmul performance as the wmma work, but the schedule is much easier to write because the driver handles a lot of stuff for you (e.g. staging through shared). TileIR is intended to be more portable across nvidia microarchitectures than using PTX directly.

Most of the code is just tileIR bitcode emission. In Halide lowering, the gputhreads dimensions are just treated as vectorized dimensions, and large vectors are passed to the backend.

Opening as draft for discussion.

abadams and others added 30 commits April 17, 2026 11:40
Resolve conflicts with main and bring the CUDA Tile IR backend back to a
state where the full correctness suite passes under
host-cuda-cuda_capability_120-cuda_tile_ir (host and PTX CUDA also pass).

Notable changes on top of the merge:
- Target bytecode 13.4 and use alloca for per-thread local storage.
- Add Func::gpu_min_resident_blocks scheduling directive (occupancy hint).
- Emit tile stores for output instead of scalar stores.
- Thread register tiles and memory tokens through For/If regions,
  restoring the outer token after reduce regions.
- Native transpose, row-wise VectorReduce, power-of-two checks on
  concat/slice fast paths, nested ramp/broadcast support.
- Emit tile IR assert for AssertStmt in kernels.
- LICM no longer lifts expressions containing any vector subexpression.
- lower_mux only unwraps scalar broadcast indices.
- Skip wmma tests and gpu_thread_barrier under tile IR.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Factor region capture and carried-value handling into shared helpers,
merge register tile bookkeeping into one record, build VectorReduce
bodies from Halide Exprs with identities from Type::max/min, drop
RewrapInnermost from FuseGPUThreadLoops, and tidy RemapCUDATileIRLoops.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Unify binary/unary/comparison emission, make Call lowering table-driven,
share concat/extract helpers for shuffles, simplify Cast, atomics, block
id lookup, pointer casts and buffer element type tracking.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Restructure the LowerMma matcher as a single function with early returns,
decompose linear expressions by substitution, and let emit_op take an op's
leading varint fields. Add write_varints, write_list and optional-operand
helpers for the remaining encodings. The generated bytecode is unchanged.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Require constant operand strides when matching, as the codegen does, and
decompose both operands' base addresses the same way. A constant k offset
in A's base (e.g. from unrolling the k loop) now goes into its k tile
coordinate rather than its pointer offset.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Integer, float, and reduction-identity constants now share one bit
encoding. float16 constants previously emitted four-byte payloads,
producing invalid bytecode, and bfloat16 was tagged as f16 because
Type::is_float() is also true for bfloat.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
ConstantOp already splats a scalar payload across a tile, so there's no
need to build vector constants with a reshape and broadcast.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…tomics

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Key the type table on its entries rather than hand-built strings, share
section framing and little-endian writing, and build the function table
before the string and type tables it refers to instead of pre-registering
its entries.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…ed helpers

The shared lower_euclidean_div/mod helpers had simplify() removed because it
canonicalized power-of-two masks back into Mod nodes. Handle power-of-two
divisors in the Tile IR pre-pass with shifts and masks instead, as CodeGen_C
does, so the shared helpers match main again.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Lower concat_bits everywhere during flatten_nested_ramps, which removes the
wrapper mutator, the Stmt lower_concat_bits export, and the backend's own
call to it.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The reduce region is generated from the same Expr combiner as the
scalarized fallback, so SaturatingAdd (identity zero) no longer needs to
be scalarized. Checked with a vectorized atomic saturating_add reduction
on uint8 and uint16.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Move the ReturnOp into the emitter, shadow buffer pointers with their
aligned versions, and pass the tensor view operands as op fields.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…ister tile accessors

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Add an overview comment to CodeGen_TileIR_Dev.cpp describing the
lowering passes, classes, and runtime path, and clarify related comments
in LICM, PartitionLoops, and TileIR.h.

A total VectorReduce of a non-power-of-two vector reduced the padding
lanes too, which gave wrong answers for min and max. Select the identity
into the padding lanes first. Add a regression test.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Atomic RMW ops on non-power-of-two vectors pass the padding mask, so
  the padding lanes no longer write past the end of the buffer.
- The compare-and-swap fallback runs one scalar CAS loop per lane, and
  threads the memory token through the loop. It previously passed a
  vector condition to cuda_tile.if, which the driver rejected.
- LowerMma only matches floating-point products. mmaf rejects integer
  operands.
- Float not-equal uses an unordered comparison, so it is true for NaN.
- trunc is select(x < 0, ceil(x), floor(x)) rather than a round trip
  through int32, which was wrong for magnitudes beyond 2^31 and inf.

Adds gpu_vectorized_atomics and gpu_integer_matmul tests, and large
inputs to the round test.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
abadams and others added 10 commits November 25, 2026 14:26
Buffer parameters gain device_alignment()/set_device_alignment(), the
device-side counterpart of host_alignment. It defaults to the element
size, and is serialized alongside host_alignment.

PTX codegen used host_alignment to reason about device pointers, which
says nothing about them. It now uses device_alignment, via a new
CodeGen_LLVM::external_buffer_alignment hook. The PTX rewrite of
4-wide 32-bit loads and stores into 128-bit accesses also only
considered the alignment of the index, so a device crop offset by a
non-multiple of 16 bytes (e.g. one element of a float buffer) failed
with CUDA_ERROR_MISALIGNED_ADDRESS when the buffer's min was
constrained. That rewrite now requires a 16-byte-aligned base pointer.

A requested device alignment is checked at runtime by a new
halide_device_check_alignment, injected after each copy_to_device or
device_malloc the pipeline does for the buffer. External buffers start
in an unknown state, so the first device use always goes through one of
these, which covers buffers that arrive with no device allocation.
The check asks the device interface for the pointer's alignment
through a new device_alignment member of
halide_device_interface_impl_t. Only CUDA implements it; on other
device APIs requesting a device alignment is a runtime error. A
misaligned pointer produces the new halide_error_code_unaligned_device_ptr
(-50).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Binding constant types in the matcher as full Types made
correctness_simplify execute 2.2% more instructions than main, because
comparing Types also checks handle and struct metadata, which bound
constants never have. Restoring the code+bits+lanes BoundConstType,
widened to 32-bit lanes, brings that to +0.2%, and lowering
local_laplacian from +0.44% to +0.15%.

Type::hash packs the low 16 bits of lanes above code and bits, matching
main's hash for any lane count main supports.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…le_ir

# Conflicts:
#	src/IRMatch.h
#	src/Type.h
… into abadams/tile_ir

# Conflicts:
#	src/CodeGen_GPU_Dev.h
#	src/Func.cpp
#	src/Func.h
#	test/correctness/gpu_min_resident_blocks.cpp
The operands only ever live on the device, and PTX codegen now takes
pointer alignment from device_alignment.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Decomposing by substitution needed the simplifier to prove
e == a * var + b, which it can't do for indices like
(y * 64 - min) * 1024. Matrix multiplies on buffers with unconstrained
mins fell back to a vector reduction, which made the cuda_mat_mul tile IR
kernel about 500x slower.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@codecov

codecov Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 20.30075% with 530 lines in your changes missing coverage. Please review.
✅ Project coverage is 71.78%. Comparing base (e9485e1) to head (5f24add).
⚠️ Report is 13 commits behind head on main.

Files with missing lines Patch % Lines
src/TileIR.cpp 0.00% 226 Missing ⚠️
src/CodeGen_Vulkan_Dev.cpp 16.19% 168 Missing and 8 partials ⚠️
src/RemapCUDATileIRLoops.cpp 0.00% 35 Missing ⚠️
src/SpirvIR.cpp 0.00% 22 Missing ⚠️
src/TileIR.h 0.00% 14 Missing ⚠️
src/Lower.cpp 10.00% 6 Missing and 3 partials ⚠️
src/OffloadGPULoops.cpp 33.33% 3 Missing and 3 partials ⚠️
src/Target.cpp 44.44% 4 Missing and 1 partial ⚠️
src/DeviceInterface.cpp 20.00% 1 Missing and 3 partials ⚠️
src/Func.cpp 63.63% 3 Missing and 1 partial ⚠️
... and 13 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #9733      +/-   ##
==========================================
- Coverage   73.24%   71.78%   -1.47%     
==========================================
  Files         266      270       +4     
  Lines       83749    84667     +918     
  Branches    20573    20937     +364     
==========================================
- Hits        61346    60778     -568     
- Misses      15859    17305    +1446     
- Partials     6544     6584      +40     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

halide-ci Bot and others added 19 commits December 1, 2026 05:24
…ser tokens

- Emit all allocas at kernel entry. tileiras implements allocas with
  device-side malloc, so an alloca inside a loop allocated on every
  iteration and eventually failed (harris).
- CSE intrinsics after lower_intrinsic, before codegen.
- Lower any shuffle whose output lane bits copy or ignore source lane
  bits (interleaves, strided/aligned slices, transposes, broadcasts) as
  reshape + extract + permute + broadcast, instead of per-element
  extracts.
- Loads of buffers the kernel never writes take no memory token. Other
  loads order after the last write and are joined into the token used
  by the next write, so loads no longer serialize against each other.
  Regions that don't write memory carry only a joined read token.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Stencil stages are compute_root kernels over 32x8 tiles, with cheap
stages inlined into them, which avoids per-block allocations.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…nv, hist, unsharp, interpolate, conv_layer, and harris

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Buffers that aren't pipeline parameters or embedded images come from
  halide_device_malloc, so assume they are 128-byte aligned. Pipeline
  parameters still use their device_alignment, and allocas their own
  alignment. This lets tileiras vectorize and use TMA for internal
  buffers.
- Contract a float Add of a Mul into an fma, like the LLVM backends do.
- A load whose index has zero-stride dimensions loads each distinct
  element once and broadcasts it, instead of gathering through a tile of
  repeated pointers.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
tileiras doesn't use tensor cores for f32 mma, so instead compute a 4x4
pixel tile per block with plain fmas. rfactor splits the reduction over
input channels four ways so the inputs load as aligned 16-byte vectors,
and unrolling the filter taps reuses them across taps. 0.85 ms on an
RTX 5060 Ti, vs 3.9 ms before and 0.78 ms for the CUDA backend.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Define the meaning of a vector Store inside an Atomic node: it is applied
one lane at a time, in an unspecified order, with its value re-evaluated
before storing each lane. A data-dependent update like f[g[x]] += b, whose
lanes may alias, can then be vectorized as a single vector store inside
the Atomic node instead of being scalarized.

- VectorizeLoops: when the load and store indices of an atomic
  read-modify-write are identical vectors but not multiramps, emit a
  vector store. Also accept a constant right-hand side, not just a lifted
  variable.
- RemoveUnnecessaryAtomics: keep an Atomic node that protects a vector
  store whose value reads the stored buffer and whose lanes may alias,
  since dropping it would change the result.
- Tile IR: lower intrinsics such as widen_right_add before matching an
  atomic RMW, so the update becomes a tile atomic_rmw rather than
  per-lane CAS loops.

The Tile IR hist app goes from 0.93ms to 0.126ms
(RTX 5060 Ti).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Make the software round-to-nearest-even return its input for floats
  that are already integers (and NaN/inf), rather than overflowing the
  conversion to an int. Fixes correctness_round on targets without a
  native round instruction.
- Build mat_mul_tileir in the cuda_mat_mul CMake build, and only run it
  on compute capability 12.0, which it is compiled for.
- Skip gpu_vectorized_total_reduction on Metal and WebGPU, which lack
  atomics, and restrict tile_ir_matmul to CUDA and the CPU.
- Add tile_ir_matmul to the CMake test list.
- clang-tidy fixes.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
A vectorized Atomic body now behaves as if it were run once per vector
lane, with every store predicated to that lane, and all stores in the
body must have the same number of lanes (asserted in Atomic::make).

RemoveUnnecessaryAtomics now considers the whole body: an Atomic with
vector stores is only dropped if the body doesn't read any buffer it
stores to, except for a single store with non-aliasing lanes that reads
the stored buffer only at its own index and not through a cross-lane op.

The aliased-slice path of atomic vectorization now wraps each slice's
store in its own Atomic node, since each was an independent atomic
update in the scalar code.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
A vector condition from an outer vectorized loop's GuardWithIf wrapped
around an inner vectorized loop couldn't be turned into a predicate, so
the whole region was scalarized. Sink such conditions into the inner
loop instead, where they widen to the full vector.

The sunk guard then hit a second limitation: bounds_of_lanes had no case
for broadcasts of vectors, so the all-lanes-true check for a likely
condition became an unsimplifiable vector_reduce, which
PredicateLoadStore refuses to predicate. A broadcast has the same lane
bounds as its value.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Rather than predicating the already-vectorized branches of an
IfThenElse with a vector condition (which failed whenever the branch
contained nested vectorized loops with more lanes), carry the scalar
condition down as a pending predicate and vectorize it afresh at each
Load and Store, so it picks up the lanes of the innermost vectorized
loop around that access. This handles intervening lets, serial loops,
and nested vectorized loops, and replaces the earlier special case
that sank the if into a directly nested vectorized loop.

The if is still scalarized if anything under it can't be predicated:
scalar stores, impure calls, atomics, vector reductions, scalarized
inner code, or mismatched lane counts.

vectorize_inner_of_scalarization now vectorizes y fully, and the
stride -1 case in predicated_store_load produces one fewer tail
branch (2 predicated stores and 4 loads instead of 3 and 6).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
A store that doesn't depend on the vectorized variable is already
executed once per vector rather than once per lane. Under a vector
condition, execute it once if any lane is active, rather than
scalarizing the whole if. Non-idempotent cases remain protected by the
Atomic check, and without an atomic they are already races.

Also use stack-allocated custom lowering passes in vectorize_nested.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…input

- Derive get_type_idx from get_1d_tile_type_idx and use Util's
  next_power_of_two.
- Compute linear_decomp's coefficient as a finite difference in the
  variable instead of recursing over Add/Sub/Mul.
- Drop the single-vector special case in emit_bit_permute_shuffle;
  emit_concat of one piece returns it unchanged.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
An extract-element is a general shuffle with one index, reshaped to a
scalar, so emit_extract and emit_extract_1d are no longer needed.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The string, type, and constant sections are each a count, an offset
table, and data. Build each as data plus offsets and write them with one
helper. This also stops ConstantPool encoding every size varint twice.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Inline the single-use helpers that the code-bits complexity measure
scores lower when inlined: split_off_const, tile_coord,
emit_tma_matrix_load, the stack allocation planning, write_typed_attr,
emit_atomic_cas_loop, emit_broadcast_load, emit_tile_store,
is_promotable, emit_nested_ramp, block_id and remap_thread_loop. Also
replace the shared indexed-section helper in TileIR.cpp with a
restructure of the constant pool alone, which scores lower.

Generated bytecode is unchanged.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant