Skip to content

feat(cutile): pointer operands for foreign tile-library calls - #1749

Merged
nvlcambier merged 1 commit into
NVIDIA:mainfrom
nvlcambier:lcambier/ffi-tile-pointers
Nov 19, 2026
Merged

nvlcambier merged 1 commit into
NVIDIA:mainfrom
nvlcambier:lcambier/ffi-tile-pointers

Conversation

@nvlcambier

@nvlcambier nvlcambier commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Why

Some tile-library functions work on global memory directly. They read input from it, write output to it, or take a scratch buffer. Their Tile IR declarations take a rank-0 tile<ptr<T>> operand. #[cutile::foreign] accepted only tiles and scalars, so cuTile Rust could not declare or call these functions. cuTile Python supports them through Array.foreign_pointer, and Tile C++ through ct::tile<T*, ct::shape<>>.

What

  • Declarations take raw pointers. In a #[cutile::foreign] declaration, a *const E or *mut E parameter lowers to a rank-0 tile<ptr<E>> operand of preview$call. This follows the usual Rust FFI split: an extern declaration takes raw pointers, and a wrapper takes tensors and states the remaining obligations.
    • A pointer operand is always in, as in Tile IR.
    • *mut documents that the library writes through the pointer. rustc rejects a *const where *mut is declared.
    • These are errors: #[inout] pointers, pointer results, and pointers to non-element types.
  • subtensor_mut_ptr() on a mutable tensor (ranks 1–3) returns the address of the current tile block's writable sub-tensor, the element load() reads first. A wrapper that takes &mut Tensor therefore gives each block its own memory, like load and store. It is not named as_mut_ptr because, unlike for slices, it is not the same address as as_ptr().
    • as_ptr() still returns the base of the whole view.
    • Two compiler ops compute the offset: get_static_extent (the tile's static extent) and get_tensor_stride (the view's static or dynamic stride).
    • A cast fix lets tile_to_pointer work inside generic helpers.
  • Ordering needs no new design. Foreign calls were already ordered with every memory access. A new test checks that a load after a call reads what the library wrote through a pointer, and that the library sees every store before the call.
  • Docs: a "Pointer operands" section in the tile-library guide, with examples taken from the test library, and a CHANGELOG entry.

Tests

  • Parser unit tests: pointer parameters are in operands; the rejected forms give clear errors.

  • IR tests (foreign_calls.rs):

    • *const and *mut operands lower to tile<ptr<…>>;
    • a generic pointee is instantiated;
    • u8 and i8 pointees both become ptr<i8>.
  • An ordering test for accesses around a pointer-operand call.

  • 3 UI tests: a #[inout] pointer, a pointer result, and a *const passed where *mut is declared.

  • GPU tests (static_tilelib). The static test tile library gains store_to (writes through a pointer) and load_from (reads through a pointer). Their SIMT side receives the pointer by value from a rank-0 local fragment. The GPU tests check:

    • rank-1, rank-2 (3 × 2 grid) and rank-3 (2 × 3 × 2 grid) block tiles from subtensor_mut_ptr, so every block-id axis contributes to the address;
    • a pointer offset from as_ptr;
    • in each case, several tile blocks, with the results checked on the host.

    Like the existing static_tilelib tests, these need a tileiras with Tile IR 13.5 foreign calls. With an older tileiras they print SKIP and pass; the CUDA 13.5 GPU lane sets CUTILE_REQUIRE_TILELIB=1, so there they must run.

Review follow-up

subtensor_mut_ptr offsets are computed in i64

The offset block id × tile extent × stride was computed in i32. For a [32769, 65536] u8 tensor in [1, 65536] tiles, block 32768 got −2³¹ instead of +2³¹, a pointer before the allocation. Each factor is now sign-extended to i64 before the products and the sum, and the base is offset with offset_tile.

  • foreign_calls.rs: the offsets of a rank-2 byte tensor are tile<i64>, and no product or sum that feeds them is in i32.
  • gpu/subtensor_mut_ptr.rs (runs in CI, needs no tile library): each block writes a marker through its pointer, on both sides of the 2³¹-element boundary.
    • Rank 2 is the reviewer's case, where one product overflows.
    • Rank 3, [2, 16385, 65536], keeps every per-axis term in i32 range, but their sum crosses 2³¹.
    • Both tests fail with an illegal address on the old arithmetic.

The book's wrapper is unsafe

subtensor_mut_ptr does not mask the out-of-bounds part of a partial tile, as load and store do. The book's safe store_tile wrapper wrote 31 elements out of bounds for a [33] tensor in [32] tiles. It is now unsafe fn, with a # Safety section that requires a whole, contiguous sub-tensor.

Renamed to subtensor_mut_ptr; safety contracts live where memory is accessed

  • block_tile_ptr() / BlockTilePtr are now subtensor_mut_ptr() / SubtensorMutPtr, matching how the docs describe each block's writable sub-tensor (gpu/block_tile_ptr.rs is now gpu/subtensor_mut_ptr.rs).
  • Getting the pointer stays safe, like <[T]>::as_mut_ptr. Its docs no longer place obligations on the caller of the getter: they state the pointer's properties (no bounds, not contiguous in general) and that the bounds, contiguity and access requirements belong in the # Safety contract of the function that reads or writes through it.
  • The book's store_to / load_from declarations (and the test library's) now carry that full contract: valid for writes (reads) of 32 contiguous f32 inside one allocation, the library does not check bounds, and no other block accesses them during the call. The round_trip kernel and store_tile wrapper name the contract each SAFETY comment meets.

Rebased onto main

Rebased and squashed onto current main, which builds the test tile library from its .mlir sources in CI (#1813): the branch's updates to the prebuilt .tilebc files are dropped, and the .mlir sources carry store_to / load_from.

Fix: one cache key per set of tile libraries

Why

While validating this PR, static_tilelib::global_accesses_after_a_foreign_call_execute (already on main) failed about 1 run in 5. It wasn't a tileiras bug, or a problem with ordering after foreign calls. It failed every time (15/15) whenever default_tile_libraries_link_every_kernel ran next to it:

  1. That test sets the process-wide default libraries to the same test_lib.tilelib the other test's launch already names.
  2. CompileOptions::with_default_tile_libraries appends the defaults to the launch's list, so the list became [tilelib, tilelib] instead of [tilelib].
  3. The in-memory cache key (TileFunctionKey) included that list as written. Two lists meant two keys, so the kernel compiled a second time and a second module was loaded.
  4. Each module has its own copy of every Global. The second launch's counter started at 0 instead of 2, and the test failed (CUTILE_JIT_LOG shows two compiles of the kernel).

This is a real bug, not only a flaky test. The guide says that naming a library that is already a default "changes nothing". Instead it cost a recompile and split a kernel's Global state between modules. Naming the same library through another path (relative or absolute, dir/./lib) did the same. CI didn't catch it because its tileiras was 13.3 at the time, so static_tilelib skipped there.

What

The key's compile_options now has an empty tile_libraries. The libraries are identified by tile_libraries_digest alone, which was already in the key and is taken over the resolved, canonical, de-duplicated libraries: paths, contents, dependencies and settings. Specialization keeps the full options, and compiles and computes the L2 key with them. The on-disk L2 key already hashed the linked libraries, so it does not change.

Tests

  • one_set_of_tile_libraries_is_one_cache_key runs in CI. It needs no tile-library toolchain, because computing a key only hashes the files.
    • A duplicated library, a path through ., and a different order give one key.
    • No library, one more library, or a rebuilt library still give different keys.
  • a_default_library_named_again_keeps_the_cache_key (13.5): a launch that names a default library again keys like the same launch without the default.
  • Both tests fail on the old key. The previously failing pair now passes 15/15, and static_tilelib passes 10/10.

Validation

  • After the rebase: scripts/run_cpu_tests.sh passes; static_tilelib and subtensor_mut_ptr GPU tests pass (24/24) with a 13.5 tileiras on an A100 and CUTILE_REQUIRE_TILELIB=1; foreign_calls (29) and foreign_ordering (23) pass; clippy -D warnings is clean.
  • scripts/run_cpu_tests.sh and the static_tilelib GPU tests pass with a 13.5 tileiras. The pointer GPU tests run (no SKIP).
  • compute-sanitizer memcheck reports 0 errors on the pointer GPU tests.
  • The whole gpu test binary passes (132 tests), and so do warmup, warmup_suite, submission_lifetimes, kernel_compiler, jit_env_overrides and foreign_calls, all with a 13.5 tileiras on an A100.
  • compute-sanitizer memcheck reports 0 errors on the subtensor_mut_ptr boundary tests, and (after the rebase) on the five pointer-operand static_tilelib tests.
  • cargo fmt --check and clippy are clean.

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Nov 5, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@nvlcambier nvlcambier changed the title Lcambier/ffi tile pointers feat(cutile): pointer operands for foreign tile-library calls Nov 5, 2026
@nvlcambier
nvlcambier force-pushed the lcambier/ffi-tile-pointers branch from ea5854b to 0d982c6 Compare November 5, 2026 21:39
@elibol

elibol commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

At a high-level: I think the name is fine. There's just an offset overflow issue + soundness bug in the documented safe wrapper. Otherwise LGTM (details below).

Agentic response:

  1. [P1] Large tensor offsets overflow. block_tile_ptr computes offsets in i32 (https://github.com/NVIDIA/cuda-rust/blob/0d982c6269b3dc765a6d762f9889857ff137ad91/cutile-rs/cutile/src/_core.rs#L4116-L4119). For a valid u8 tensor shaped [32769, 65536], partitioned into [1, 65536], I reproduced an offset of −2,147,483,648 instead of +2,147,483,648 bytes. A foreign function would receive a pointer before the allocation.

Widen operands to i64 before multiplication and addition, then use the existing pointer-offset machinery that accepts i64. Add a regression at the boundary.

  1. [P1] The documented safe wrapper can write out of bounds. The store_tile example (https://github.com/NVIDIA/cuda-rust/blob/0d982c6269b3dc765a6d762f9889857ff137ad91/cutile-rs/cutile-book/guide/tile-libraries.md#L233-L244) assumes a tile shape of [32] guarantees 32 backed elements. Partitions allow incomplete final tiles. With 33 elements partitioned into tiles of 32, Compute Sanitizer reported 31 invalid writes from that wrapper.

Make the wrapper unsafe with explicit bounds/contiguity requirements, or enforce those requirements. Document that block_tile_ptr doesn’t provide the bounds masking of ordinary tensor loads/stores.

@nvlcambier
nvlcambier force-pushed the lcambier/ffi-tile-pointers branch from 0d982c6 to 82cb737 Compare November 9, 2026 18:46
nvlcambier added a commit to nvlcambier/cuda-rust that referenced this pull request Nov 9, 2026
Addresses the review of NVIDIA#1749.

`block_tile_ptr` computed `block id x tile extent x stride` in i32. A
`[32769, 65536]` u8 tensor in `[1, 65536]` tiles gave block 32768 the
offset -2^31 instead of 2^31, a pointer before the allocation. Each
factor is now sign-extended to a rank-0 i64 tile before the products
and the sum, and the base is offset with `offset_tile`.

Tests:
- `foreign_calls`: the offsets of a rank-2 byte tensor are `tile<i64>`,
  and no product or sum feeding them is in i32.
- `gpu/block_tile_ptr`: each block writes a marker through its pointer,
  on both sides of the 2^31-element boundary. Rank 2 is the review's
  case (one product overflows). Rank 3, `[2, 16385, 65536]`, has every
  per-axis term in i32 range but their sum crossing 2^31. With i32
  products the rank-2 test fails with an illegal address; with i64
  products and an i32 sum, the rank-3 test does.

`block_tile_ptr` does not mask the out-of-bounds part of a partial
tile, as `load` and `store` do. The book's `store_tile` wrapper was safe
but wrote 31 elements out of bounds for a `[33]` tensor in `[32]`
tiles. It is now `unsafe`, with a `# Safety` section requiring a whole,
contiguous tile, and the book and the `BlockTilePtr` docs say that the
pointer carries no bounds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Leopold Cambier <[email protected]>
@nvlcambier

Copy link
Copy Markdown
Collaborator Author

/ok to test 714d396

@elibol

elibol commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator

@nvlcambier should round_trip also be an unsafe entry point, given that its pointer calls require full contiguous tiles (like store_tile)?

@elibol elibol added the cutile-rs Tile programming model: cutile crates, compiler, macros, IR, kernels, and book label Nov 12, 2026
@nvlcambier
nvlcambier force-pushed the lcambier/ffi-tile-pointers branch from 714d396 to 327ba94 Compare November 13, 2026 00:35
nvlcambier added a commit to nvlcambier/cuda-rust that referenced this pull request Nov 13, 2026
Addresses the review of NVIDIA#1749.

`block_tile_ptr` computed `block id x tile extent x stride` in i32. A
`[32769, 65536]` u8 tensor in `[1, 65536]` tiles gave block 32768 the
offset -2^31 instead of 2^31, a pointer before the allocation. Each
factor is now sign-extended to a rank-0 i64 tile before the products
and the sum, and the base is offset with `offset_tile`.

Tests:
- `foreign_calls`: the offsets of a rank-2 byte tensor are `tile<i64>`,
  and no product or sum feeding them is in i32.
- `gpu/block_tile_ptr`: each block writes a marker through its pointer,
  on both sides of the 2^31-element boundary. Rank 2 is the review's
  case (one product overflows). Rank 3, `[2, 16385, 65536]`, has every
  per-axis term in i32 range but their sum crossing 2^31. With i32
  products the rank-2 test fails with an illegal address; with i64
  products and an i32 sum, the rank-3 test does.

`block_tile_ptr` does not mask the out-of-bounds part of a partial
tile, as `load` and `store` do. The book's `store_tile` wrapper was safe
but wrote 31 elements out of bounds for a `[33]` tensor in `[32]`
tiles. It is now `unsafe`, with a `# Safety` section requiring a whole,
contiguous tile, and the book and the `BlockTilePtr` docs say that the
pointer carries no bounds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Leopold Cambier <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Nov 13, 2026

Copy link
Copy Markdown

/ok to test 327ba94bb1a75a8fd7f4d563647391a832fa613b

@nvlcambier, there was an error processing your request: E2

See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/2/

@nvlcambier

Copy link
Copy Markdown
Collaborator Author

/ok to test 327ba94

@nvlcambier
nvlcambier force-pushed the lcambier/ffi-tile-pointers branch from 327ba94 to c3bc360 Compare November 19, 2026 00:02
@nvlcambier

Copy link
Copy Markdown
Collaborator Author

/ok to test c3bc360

@elibol elibol left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This LGTM!

A `#[cutile::foreign]` declaration can take a raw pointer, `*const E` or
`*mut E`, which lowers to a rank-0 `tile<ptr<E>>` operand of
`preview$call`, the form Tile IR uses for a library function that reads
or writes global memory. A pointer operand is always `in`; `*mut` states
that the library writes through it, and rustc rejects a `*const` where
`*mut` is declared. `#[inout]` pointers and pointer results are errors.

`subtensor_mut_ptr()` on a mutable tensor (ranks 1 to 3, trait
`SubtensorMutPtr`) returns the address of the current tile block's
writable sub-tensor, the element `load()` reads first, so a wrapper
taking `&mut Tensor` passes each block its own memory. `as_ptr()` stays
the base of the whole view. The offset is `block id x tile extent x
stride` per axis, computed in i64, so tensors of more than `i32::MAX`
elements get the right address. Two compiler ops, `get_static_extent`
and `get_tensor_stride`, supply the tile shape and the view's static or
dynamic strides.

Getting the pointer is safe, like `<[T]>::as_mut_ptr`. The pointer
carries no bounds and the sub-tensor is not contiguous in general, so
the bounds, contiguity and access requirements belong in the `# Safety`
contract of the foreign function that writes through it, and of any
unsafe wrapper. The book's examples show this.

Foreign calls were already ordered with every memory access, so a load
after a call reads what the library wrote through a pointer; an ordering
test covers it.

A kernel's in-memory cache key now uses the resolved, de-duplicated tile
libraries (`tile_libraries_digest`) instead of the list as written.
Naming a default library again recompiled the kernel into a second
module with its own `Global` state.

Tests: UI tests for the rejected pointer forms; IR tests for the i64
offsets; GPU tests through the static test tile library (`store_to`,
`load_from`) for rank-1, rank-2 and rank-3 block tiles, and on both
sides of the 2^31-element boundary; cache-key tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Leopold Cambier <[email protected]>
@nvlcambier
nvlcambier force-pushed the lcambier/ffi-tile-pointers branch from c3bc360 to e1ac7db Compare November 19, 2026 14:23
@nvlcambier

Copy link
Copy Markdown
Collaborator Author

/ok to test e1ac7db

@nvlcambier
nvlcambier merged commit 8046b9e into NVIDIA:main Nov 19, 2026
43 checks passed
uurl pushed a commit to uurl/cuda-rust that referenced this pull request Nov 21, 2026
…#1749)

## Why

Some tile-library functions work on global memory directly. They read
input from it, write output to it, or take a scratch buffer. Their Tile
IR declarations take a rank-0 `tile<ptr<T>>` operand.
`#[cutile::foreign]` accepted only tiles and scalars, so cuTile Rust
could not declare or call these functions. cuTile Python supports them
through `Array.foreign_pointer`, and Tile C++ through `ct::tile<T*,
ct::shape<>>`.

## What

- **Declarations take raw pointers.** In a `#[cutile::foreign]`
declaration, a `*const E` or `*mut E` parameter lowers to a rank-0
`tile<ptr<E>>` operand of `preview$call`. This follows the usual Rust
FFI split: an `extern` declaration takes raw pointers, and a wrapper
takes tensors and states the remaining obligations.
  - A pointer operand is always `in`, as in Tile IR.
- `*mut` documents that the library writes through the pointer. rustc
rejects a `*const` where `*mut` is declared.
- These are errors: `#[inout]` pointers, pointer results, and pointers
to non-element types.
- **`subtensor_mut_ptr()` on a mutable tensor (ranks 1–3) returns the
address of the current tile block's writable sub-tensor**, the element
`load()` reads first. A wrapper that takes `&mut Tensor` therefore gives
each block its own memory, like `load` and `store`. It is not named
`as_mut_ptr` because, unlike for slices, it is not the same address as
`as_ptr()`.
  - `as_ptr()` still returns the base of the whole view.
- Two compiler ops compute the offset: `get_static_extent` (the tile's
static extent) and `get_tensor_stride` (the view's static or dynamic
stride).
  - A cast fix lets `tile_to_pointer` work inside generic helpers.
- **Ordering needs no new design.** Foreign calls were already ordered
with every memory access. A new test checks that a load after a call
reads what the library wrote through a pointer, and that the library
sees every store before the call.
- **Docs:** a "Pointer operands" section in the tile-library guide, with
examples taken from the test library, and a CHANGELOG entry.

## Tests

- **Parser unit tests:** pointer parameters are `in` operands; the
rejected forms give clear errors.
- **IR tests (`foreign_calls.rs`):**
  - `*const` and `*mut` operands lower to `tile<ptr<…>>`;
  - a generic pointee is instantiated;
  - `u8` and `i8` pointees both become `ptr<i8>`.
- **An ordering test** for accesses around a pointer-operand call.
- **3 UI tests:** a `#[inout]` pointer, a pointer result, and a `*const`
passed where `*mut` is declared.
- **GPU tests (`static_tilelib`).** The static test tile library gains
`store_to` (writes through a pointer) and `load_from` (reads through a
pointer). Their SIMT side receives the pointer by value from a rank-0
local fragment. The GPU tests check:
- rank-1, rank-2 (3 × 2 grid) and rank-3 (2 × 3 × 2 grid) block tiles
from `subtensor_mut_ptr`, so every block-id axis contributes to the
address;
  - a pointer offset from `as_ptr`;
- in each case, several tile blocks, with the results checked on the
host.

Like the existing `static_tilelib` tests, these need a `tileiras` with
Tile IR 13.5 foreign calls. With an older `tileiras` they print SKIP and
pass; the CUDA 13.5 GPU lane sets `CUTILE_REQUIRE_TILELIB=1`, so there
they must run.

## Review follow-up

### `subtensor_mut_ptr` offsets are computed in `i64`

The offset `block id × tile extent × stride` was computed in `i32`. For
a `[32769, 65536]` `u8` tensor in `[1, 65536]` tiles, block 32768 got
−2³¹ instead of +2³¹, a pointer before the allocation. Each factor is
now sign-extended to `i64` before the products and the sum, and the base
is offset with `offset_tile`.

- `foreign_calls.rs`: the offsets of a rank-2 byte tensor are
`tile<i64>`, and no product or sum that feeds them is in `i32`.
- `gpu/subtensor_mut_ptr.rs` (runs in CI, needs no tile library): each
block writes a marker through its pointer, on both sides of the
2³¹-element boundary.
  - Rank 2 is the reviewer's case, where one product overflows.
- Rank 3, `[2, 16385, 65536]`, keeps every per-axis term in `i32` range,
but their sum crosses 2³¹.
  - Both tests fail with an illegal address on the old arithmetic.

### The book's wrapper is `unsafe`

`subtensor_mut_ptr` does not mask the out-of-bounds part of a partial
tile, as `load` and `store` do. The book's safe `store_tile` wrapper
wrote 31 elements out of bounds for a `[33]` tensor in `[32]` tiles. It
is now `unsafe fn`, with a `# Safety` section that requires a whole,
contiguous sub-tensor.

### Renamed to `subtensor_mut_ptr`; safety contracts live where memory
is accessed

- `block_tile_ptr()` / `BlockTilePtr` are now `subtensor_mut_ptr()` /
`SubtensorMutPtr`, matching how the docs describe each block's writable
sub-tensor (`gpu/block_tile_ptr.rs` is now `gpu/subtensor_mut_ptr.rs`).
- Getting the pointer stays safe, like `<[T]>::as_mut_ptr`. Its docs no
longer place obligations on the caller of the getter: they state the
pointer's properties (no bounds, not contiguous in general) and that the
bounds, contiguity and access requirements belong in the `# Safety`
contract of the function that reads or writes through it.
- The book's `store_to` / `load_from` declarations (and the test
library's) now carry that full contract: valid for writes (reads) of 32
contiguous `f32` inside one allocation, the library does not check
bounds, and no other block accesses them during the call. The
`round_trip` kernel and `store_tile` wrapper name the contract each
`SAFETY` comment meets.

### Rebased onto `main`

Rebased and squashed onto current `main`, which builds the test tile
library from its `.mlir` sources in CI (NVIDIA#1813): the branch's updates to
the prebuilt `.tilebc` files are dropped, and the `.mlir` sources carry
`store_to` / `load_from`.

## Fix: one cache key per set of tile libraries

### Why

While validating this PR,
`static_tilelib::global_accesses_after_a_foreign_call_execute` (already
on `main`) failed about 1 run in 5. It wasn't a `tileiras` bug, or a
problem with ordering after foreign calls. It failed every time (15/15)
whenever `default_tile_libraries_link_every_kernel` ran next to it:

1. That test sets the process-wide default libraries to the same
`test_lib.tilelib` the other test's launch already names.
2. `CompileOptions::with_default_tile_libraries` appends the defaults to
the launch's list, so the list became `[tilelib, tilelib]` instead of
`[tilelib]`.
3. The in-memory cache key (`TileFunctionKey`) included that list as
written. Two lists meant two keys, so the kernel compiled a second time
and a **second module** was loaded.
4. Each module has its own copy of every `Global`. The second launch's
counter started at 0 instead of 2, and the test failed (`CUTILE_JIT_LOG`
shows two compiles of the kernel).

This is a real bug, not only a flaky test. The guide says that naming a
library that is already a default "changes nothing". Instead it cost a
recompile and split a kernel's `Global` state between modules. Naming
the same library through another path (relative or absolute,
`dir/./lib`) did the same. CI didn't catch it because its `tileiras` was
13.3 at the time, so `static_tilelib` skipped there.

### What

The key's `compile_options` now has an empty `tile_libraries`. The
libraries are identified by `tile_libraries_digest` alone, which was
already in the key and is taken over the resolved, canonical,
de-duplicated libraries: paths, contents, dependencies and settings.
`Specialization` keeps the full options, and compiles and computes the
L2 key with them. The on-disk L2 key already hashed the linked
libraries, so it does not change.

### Tests

- `one_set_of_tile_libraries_is_one_cache_key` runs in CI. It needs no
tile-library toolchain, because computing a key only hashes the files.
- A duplicated library, a path through `.`, and a different order give
one key.
- No library, one more library, or a rebuilt library still give
different keys.
- `a_default_library_named_again_keeps_the_cache_key` (13.5): a launch
that names a default library again keys like the same launch without the
default.
- Both tests fail on the old key. The previously failing pair now passes
15/15, and `static_tilelib` passes 10/10.

## Validation

- After the rebase: `scripts/run_cpu_tests.sh` passes; `static_tilelib`
and `subtensor_mut_ptr` GPU tests pass (24/24) with a 13.5 `tileiras` on
an A100 and `CUTILE_REQUIRE_TILELIB=1`; `foreign_calls` (29) and
`foreign_ordering` (23) pass; clippy `-D warnings` is clean.
- `scripts/run_cpu_tests.sh` and the `static_tilelib` GPU tests pass
with a 13.5 `tileiras`. The pointer GPU tests run (no SKIP).
- compute-sanitizer memcheck reports 0 errors on the pointer GPU tests.
- The whole `gpu` test binary passes (132 tests), and so do `warmup`,
`warmup_suite`, `submission_lifetimes`, `kernel_compiler`,
`jit_env_overrides` and `foreign_calls`, all with a 13.5 `tileiras` on
an A100.
- compute-sanitizer memcheck reports 0 errors on the `subtensor_mut_ptr`
boundary tests, and (after the rebase) on the five pointer-operand
`static_tilelib` tests.
- `cargo fmt --check` and clippy are clean.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: Leopold Cambier <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Signed-off-by: Raul Estrada <[email protected]>
uurl pushed a commit to uurl/cuda-rust that referenced this pull request Nov 21, 2026
…#1749)

## Why

Some tile-library functions work on global memory directly. They read
input from it, write output to it, or take a scratch buffer. Their Tile
IR declarations take a rank-0 `tile<ptr<T>>` operand.
`#[cutile::foreign]` accepted only tiles and scalars, so cuTile Rust
could not declare or call these functions. cuTile Python supports them
through `Array.foreign_pointer`, and Tile C++ through `ct::tile<T*,
ct::shape<>>`.

## What

- **Declarations take raw pointers.** In a `#[cutile::foreign]`
declaration, a `*const E` or `*mut E` parameter lowers to a rank-0
`tile<ptr<E>>` operand of `preview$call`. This follows the usual Rust
FFI split: an `extern` declaration takes raw pointers, and a wrapper
takes tensors and states the remaining obligations.
  - A pointer operand is always `in`, as in Tile IR.
- `*mut` documents that the library writes through the pointer. rustc
rejects a `*const` where `*mut` is declared.
- These are errors: `#[inout]` pointers, pointer results, and pointers
to non-element types.
- **`subtensor_mut_ptr()` on a mutable tensor (ranks 1–3) returns the
address of the current tile block's writable sub-tensor**, the element
`load()` reads first. A wrapper that takes `&mut Tensor` therefore gives
each block its own memory, like `load` and `store`. It is not named
`as_mut_ptr` because, unlike for slices, it is not the same address as
`as_ptr()`.
  - `as_ptr()` still returns the base of the whole view.
- Two compiler ops compute the offset: `get_static_extent` (the tile's
static extent) and `get_tensor_stride` (the view's static or dynamic
stride).
  - A cast fix lets `tile_to_pointer` work inside generic helpers.
- **Ordering needs no new design.** Foreign calls were already ordered
with every memory access. A new test checks that a load after a call
reads what the library wrote through a pointer, and that the library
sees every store before the call.
- **Docs:** a "Pointer operands" section in the tile-library guide, with
examples taken from the test library, and a CHANGELOG entry.

## Tests

- **Parser unit tests:** pointer parameters are `in` operands; the
rejected forms give clear errors.
- **IR tests (`foreign_calls.rs`):**
  - `*const` and `*mut` operands lower to `tile<ptr<…>>`;
  - a generic pointee is instantiated;
  - `u8` and `i8` pointees both become `ptr<i8>`.
- **An ordering test** for accesses around a pointer-operand call.
- **3 UI tests:** a `#[inout]` pointer, a pointer result, and a `*const`
passed where `*mut` is declared.
- **GPU tests (`static_tilelib`).** The static test tile library gains
`store_to` (writes through a pointer) and `load_from` (reads through a
pointer). Their SIMT side receives the pointer by value from a rank-0
local fragment. The GPU tests check:
- rank-1, rank-2 (3 × 2 grid) and rank-3 (2 × 3 × 2 grid) block tiles
from `subtensor_mut_ptr`, so every block-id axis contributes to the
address;
  - a pointer offset from `as_ptr`;
- in each case, several tile blocks, with the results checked on the
host.

Like the existing `static_tilelib` tests, these need a `tileiras` with
Tile IR 13.5 foreign calls. With an older `tileiras` they print SKIP and
pass; the CUDA 13.5 GPU lane sets `CUTILE_REQUIRE_TILELIB=1`, so there
they must run.

## Review follow-up

### `subtensor_mut_ptr` offsets are computed in `i64`

The offset `block id × tile extent × stride` was computed in `i32`. For
a `[32769, 65536]` `u8` tensor in `[1, 65536]` tiles, block 32768 got
−2³¹ instead of +2³¹, a pointer before the allocation. Each factor is
now sign-extended to `i64` before the products and the sum, and the base
is offset with `offset_tile`.

- `foreign_calls.rs`: the offsets of a rank-2 byte tensor are
`tile<i64>`, and no product or sum that feeds them is in `i32`.
- `gpu/subtensor_mut_ptr.rs` (runs in CI, needs no tile library): each
block writes a marker through its pointer, on both sides of the
2³¹-element boundary.
  - Rank 2 is the reviewer's case, where one product overflows.
- Rank 3, `[2, 16385, 65536]`, keeps every per-axis term in `i32` range,
but their sum crosses 2³¹.
  - Both tests fail with an illegal address on the old arithmetic.

### The book's wrapper is `unsafe`

`subtensor_mut_ptr` does not mask the out-of-bounds part of a partial
tile, as `load` and `store` do. The book's safe `store_tile` wrapper
wrote 31 elements out of bounds for a `[33]` tensor in `[32]` tiles. It
is now `unsafe fn`, with a `# Safety` section that requires a whole,
contiguous sub-tensor.

### Renamed to `subtensor_mut_ptr`; safety contracts live where memory
is accessed

- `block_tile_ptr()` / `BlockTilePtr` are now `subtensor_mut_ptr()` /
`SubtensorMutPtr`, matching how the docs describe each block's writable
sub-tensor (`gpu/block_tile_ptr.rs` is now `gpu/subtensor_mut_ptr.rs`).
- Getting the pointer stays safe, like `<[T]>::as_mut_ptr`. Its docs no
longer place obligations on the caller of the getter: they state the
pointer's properties (no bounds, not contiguous in general) and that the
bounds, contiguity and access requirements belong in the `# Safety`
contract of the function that reads or writes through it.
- The book's `store_to` / `load_from` declarations (and the test
library's) now carry that full contract: valid for writes (reads) of 32
contiguous `f32` inside one allocation, the library does not check
bounds, and no other block accesses them during the call. The
`round_trip` kernel and `store_tile` wrapper name the contract each
`SAFETY` comment meets.

### Rebased onto `main`

Rebased and squashed onto current `main`, which builds the test tile
library from its `.mlir` sources in CI (NVIDIA#1813): the branch's updates to
the prebuilt `.tilebc` files are dropped, and the `.mlir` sources carry
`store_to` / `load_from`.

## Fix: one cache key per set of tile libraries

### Why

While validating this PR,
`static_tilelib::global_accesses_after_a_foreign_call_execute` (already
on `main`) failed about 1 run in 5. It wasn't a `tileiras` bug, or a
problem with ordering after foreign calls. It failed every time (15/15)
whenever `default_tile_libraries_link_every_kernel` ran next to it:

1. That test sets the process-wide default libraries to the same
`test_lib.tilelib` the other test's launch already names.
2. `CompileOptions::with_default_tile_libraries` appends the defaults to
the launch's list, so the list became `[tilelib, tilelib]` instead of
`[tilelib]`.
3. The in-memory cache key (`TileFunctionKey`) included that list as
written. Two lists meant two keys, so the kernel compiled a second time
and a **second module** was loaded.
4. Each module has its own copy of every `Global`. The second launch's
counter started at 0 instead of 2, and the test failed (`CUTILE_JIT_LOG`
shows two compiles of the kernel).

This is a real bug, not only a flaky test. The guide says that naming a
library that is already a default "changes nothing". Instead it cost a
recompile and split a kernel's `Global` state between modules. Naming
the same library through another path (relative or absolute,
`dir/./lib`) did the same. CI didn't catch it because its `tileiras` was
13.3 at the time, so `static_tilelib` skipped there.

### What

The key's `compile_options` now has an empty `tile_libraries`. The
libraries are identified by `tile_libraries_digest` alone, which was
already in the key and is taken over the resolved, canonical,
de-duplicated libraries: paths, contents, dependencies and settings.
`Specialization` keeps the full options, and compiles and computes the
L2 key with them. The on-disk L2 key already hashed the linked
libraries, so it does not change.

### Tests

- `one_set_of_tile_libraries_is_one_cache_key` runs in CI. It needs no
tile-library toolchain, because computing a key only hashes the files.
- A duplicated library, a path through `.`, and a different order give
one key.
- No library, one more library, or a rebuilt library still give
different keys.
- `a_default_library_named_again_keeps_the_cache_key` (13.5): a launch
that names a default library again keys like the same launch without the
default.
- Both tests fail on the old key. The previously failing pair now passes
15/15, and `static_tilelib` passes 10/10.

## Validation

- After the rebase: `scripts/run_cpu_tests.sh` passes; `static_tilelib`
and `subtensor_mut_ptr` GPU tests pass (24/24) with a 13.5 `tileiras` on
an A100 and `CUTILE_REQUIRE_TILELIB=1`; `foreign_calls` (29) and
`foreign_ordering` (23) pass; clippy `-D warnings` is clean.
- `scripts/run_cpu_tests.sh` and the `static_tilelib` GPU tests pass
with a 13.5 `tileiras`. The pointer GPU tests run (no SKIP).
- compute-sanitizer memcheck reports 0 errors on the pointer GPU tests.
- The whole `gpu` test binary passes (132 tests), and so do `warmup`,
`warmup_suite`, `submission_lifetimes`, `kernel_compiler`,
`jit_env_overrides` and `foreign_calls`, all with a 13.5 `tileiras` on
an A100.
- compute-sanitizer memcheck reports 0 errors on the `subtensor_mut_ptr`
boundary tests, and (after the rebase) on the five pointer-operand
`static_tilelib` tests.
- `cargo fmt --check` and clippy are clean.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: Leopold Cambier <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Signed-off-by: Raul Estrada <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cutile-rs Tile programming model: cutile crates, compiler, macros, IR, kernels, and book

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants