Skip to content

feat(cuda-device): let a ConstantMemory table be read at a runtime index - #691

Merged
nihalpasham merged 1 commit into
NVIDIA:mainfrom
vyncint:perf/constant-memory-ref
Aug 8, 2026
Merged

nihalpasham merged 1 commit into
NVIDIA:mainfrom
vyncint:perf/constant-memory-ref

Conversation

@vyncint

@vyncint vyncint commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Closes #690.

Summary

ConstantMemory<T> had one accessor, get, returning T by value. Right for
a scalar, but it left no way to index a ConstantMemory<[T; N]> at a runtime
index: a value has no address, so the copy is spilled to the thread's local depot
— one st.local per element in every thread — and the lookup then reads
thread-private memory. #[constant] could not express the shape constant memory
exists for:

__constant__ float coeffs[256];
acc += coeffs[i & 255];      // runtime index

This adds get_ref(&self) -> &T, which borrows the storage so the index stays in
constant space.

No codegen change. A reference into a #[constant] static already keeps
address space 4 all the way down: the symbol stays addrspace(4) global in LLVM
IR (so a host set_<name> remains visible) and the read emits one
ld.const.b32. Only the safe way to obtain that reference was missing. For the
reproducer kernel, 555 PTX instructions with a 1 KiB depot become 42 with
none
.

The existing examples never showed this because they index at compile-time
constants — constant_memory_coeffs does c[0], c[1]; constant_memory
destructures let [c0, c1, c2, c3] = COEFFS.get();. SROA cleans those up
entirely. Only a runtime index falls off the cliff, so both keep using get here
and both still pass.

Safety

Safe under the contract get already relies on: device code only reads this
storage, so no &mut exists to alias it, and the host writes only between kernel
launches via cuMemcpyHtoD, synchronized out-of-band relative to device
execution. Holding a shared reference for the duration of a launch observes no
write that get would not.

Borrowing through the UnsafeCell is what keeps this honest: the storage stays
mutable as far as the compiler is concerned, so reads are not folded to the
all-zero placeholder and a set_<name> between launches stays visible. That is
the property the wrapper exists for, and the emitted ld.const.b32 confirms it
survives.

Measured

A10G, from the evidence log's nvidia-smi block:

name, compute_cap, memory.total [MiB], driver_version
NVIDIA A10G, 8.6, 23028 MiB, 595.71.05

256-entry f32 table, 64 dependent lookups per thread over 8388608 threads, 50
timed launches after 10 warmup. Every variant bit-identical against a host
reference computed with the same add order:

kernel                   reached by          index   us/launch   Glookups/s   correct
--------------------------------------------------------------------------------------
const_getval_div              get()      divergent     16048.3        33.45       yes
const_ref_div             get_ref()      divergent      7616.3        70.49       yes
global_div           const [f32; N]      divergent       321.7      1668.98       yes
const_getval_uni              get()   warp-uniform     16065.4        33.42       yes
const_ref_uni             get_ref()   warp-uniform       258.5      2076.72       yes
global_uni           const [f32; N]   warp-uniform       322.4      1665.15       yes
index pattern get() get_ref() speedup
divergent 16048.3 us 7616.3 us 2.11x
warp-uniform 16065.4 us 258.5 us 62.14x

Note the get() row barely moves between the two index patterns (16048 vs
16065): the per-thread depot copy dominates so completely that the access pattern
stops mattering. That is the signature of the defect.

The second half: .const is not simply faster memory

The same run settles which address space a table belongs in, which the docs did
not say anywhere. Constant memory is served by a broadcast-oriented cache:

index pattern .const (get_ref) .global (const [f32; N]) winner
warp-uniform 258.5 us 322.4 us .const, 1.25x
divergent 7616.3 us 321.7 us .global, 23.7x

On a warp-uniform index every lane wants the same entry and it is one broadcast —
what the constant cache is for. On a divergent index the cache serves distinct
addresses in sequence, so a warp asking for up to 32 different entries
serializes, while the same table in global memory coalesces and stays resident in
L1.

So a divergent lookup table should be a plain const TABLE: [f32; N], which
since #684 is materialized as one immutable device global read with
ld.global.nc — no host upload and no #[constant] at all. Choosing .const by
the qualifier rather than by the access pattern is a 23.7x mistake, and both the
guidance and these numbers are now in get_ref's docs.

Docs corrected

get's own advice was actively pointing at the pathology:

For large T (e.g. ConstantMemory<[f32; 1024]>) call .get() once before the
loop and reuse the local

A local reused across a runtime-indexed read is precisely what forces the array
into the depot, so the advice could not be followed to a good outcome. It now
points at get_ref instead. The module-level docs gained the two-accessor
distinction, and the module example uses get_ref.

New example

constant_memory_table measures all six combinations of {get, get_ref,
const [f32; N]} x {divergent, warp-uniform} and checks each against its own
host reference. The two index patterns are made comparable rather than merely
different: both read the input buffer once and write the output once, and the
_uni kernels seed from input[i & !(WARP - 1)] — one warp-uniform load — so
only the index's divergence varies, not the memory traffic or the arithmetic
count.

Validation

Local, all clean:

cargo fmt --check
cargo clippy --all-targets --lib --tests -- -D warnings
cargo test -p cuda-device --lib --tests
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --workspace
cargo test --doc -p cuda-device
bash scripts/check-dependency-licenses.sh            # OK, no new third-party crates
bash scripts/check-error-example-status.sh           # OK

On the A10G — scoped smoketest 9/9, 0 fail (.gpu-evidence/20260807T134040Z.log),
covering every constant-memory example plus controls:

[ 1/ 9] array_constants         ... PASS      [ 6/ 9] tma_copy       ... PASS (skipped)
[ 2/ 9] const_table_lookup      ... PASS      [ 7/ 9] uninit_const   ... PASS
[ 3/ 9] constant_memory_coeffs  ... PASS      [ 8/ 9] vecadd         ... PASS
[ 4/ 9] constant_memory_table   ... PASS      [ 9/ 9] vectorization  ... PASS
[ 5/ 9] device_global           ... PASS

I scoped rather than swept: this adds an inherent method and touches no existing
code path, so the constant-memory examples plus controls are the relevant
surface. Say the word if you would rather see the full 188.

Not verified: SASS. nvdisasm is not on the image I used, so the
instruction-level evidence here is PTX only.

Not in this PR

impl Index for ConstantMemory<[T; N]> would read better at the call site than
get_ref()[i], but it only helps arrays while get_ref also covers structs. Glad
to add it on top if you prefer that spelling.

`ConstantMemory<T>` had one accessor, `get`, returning `T` by value. That is
right for a scalar but leaves no way to index a `ConstantMemory<[T; N]>` at a
runtime index: a value has no address, so the copy is spilled to the thread's
local depot -- one `st.local` per element in every thread -- and the lookup then
reads thread-private memory. `#[constant]` could not express the shape constant
memory exists for.

Add `get_ref(&self) -> &T`, which borrows the storage in place so the index stays
in constant space. Safe under the contract `get` already relies on: device code
only reads this storage, so no `&mut` exists to alias, and the host writes only
between launches via `cuMemcpyHtoD`. Borrowing through the `UnsafeCell` keeps the
storage mutable as far as the compiler is concerned, so a `set_<name>` between
launches stays visible -- the property that makes the wrapper necessary at all.

No codegen change: a reference into a `#[constant]` static already keeps address
space 4 all the way down. The symbol stays `addrspace(4) global` in LLVM IR and
the read emits one `ld.const.b32`. Only the safe way to obtain that reference was
missing. For the reproducer kernel, 555 PTX instructions with a 1 KiB depot
become 42 with none.

Also corrects `get`'s own advice. It recommended calling `.get()` once for a
large `T` and reusing the local, which is the pathology rather than a way around
it: a local reused across a runtime-indexed read is exactly what forces the
array into the depot.

Measured on an A10G (sm_86, driver 595.71.05), 256-entry f32 table, 64 dependent
lookups per thread over 8388608 threads, 50 timed launches after 10 warmup, every
variant bit-identical against a host reference:

  index pattern    get()      get_ref()   const [f32; N]
  divergent        16048.3us    7616.3us        321.7us
  warp-uniform     16065.4us     258.5us        322.4us

So `get_ref` is 2.1x the throughput of `get` on a divergent index and 62x on a
warp-uniform one. The `get()` row barely moves between the two patterns, because
the per-thread depot copy dominates so completely that the access pattern stops
mattering.

The same measurement settles which address space a table belongs in, which the
docs did not say anywhere. Constant memory is not simply faster memory: its cache
broadcasts, so it wins on a warp-uniform index (258.5us vs 322.4us) and loses
23.7x on a divergent one (7616.3us vs 321.7us), where distinct addresses are
served in sequence while the same table in global memory coalesces and stays in
L1. A divergent lookup table should be a plain `const TABLE: [f32; N]`, which
since NVIDIA#684 is one immutable device global read with `ld.global.nc`. Both the
guidance and the numbers are now in `get_ref`'s docs.

Adds `constant_memory_table`, which measures all six combinations and checks each
against a host reference.

Closes NVIDIA#690.

Signed-off-by: Vyncint Ng <[email protected]>
@nihalpasham nihalpasham added enhancement New feature or request perf Performance of generated code or of the compiler itself documentation Improvements or additions to documentation intrinsics Device intrinsics and libdevice math mappings cuda-feature A CUDA hardware/toolkit feature (TMA, tcgen05, WGMMA) labels Aug 8, 2026
@vyncint

vyncint commented Aug 8, 2026

Copy link
Copy Markdown
Contributor Author

Note on coverage, so the evidence in this PR is not read as broader than it is.

I ran a full 190/190 sweep on the A10G for the array-constant stack
(#694 + #715 + #717) — .gpu-evidence/20260808T080039Z.log. That sweep does not
cover this PR
: get_ref is on a separate branch and was not part of it.

This PR's execution evidence remains its own scoped run, 9/9
(.gpu-evidence/20260807T134040Z.log), covering every constant-memory example
plus controls. Happy to run the full sweep for this branch too if you would rather
not merge on the scoped one — it is one box run.

@nihalpasham

Copy link
Copy Markdown
Collaborator

Gist: Not a compiler change, just the missing safe accessor. get() returns the table by value, and a value has no address, so indexing it at a runtime index forced a copy of the whole table into each thread's private memory first.

  • references into #[constant] statics already stay in constant memory all the way through the compiler; get_ref() simply gives you a safe way to obtain one.
  • the doc fix matters as much as the API: get()'s old advice actively recommended the slow pattern.

Verified on an RTX 5090 (sm_120):

  • all 6 kernels bit-correct, SUCCESS marker;
  • the new accessor compiles to a single constant-memory load with no per-thread copy, and
  • the doc's advice about when constant memory loses to global (divergent indices) reproduces on this card.

Closes #690.

Merging.

@nihalpasham
nihalpasham merged commit b803005 into NVIDIA:main Aug 8, 2026
36 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cuda-feature A CUDA hardware/toolkit feature (TMA, tcgen05, WGMMA) documentation Improvements or additions to documentation enhancement New feature or request intrinsics Device intrinsics and libdevice math mappings perf Performance of generated code or of the compiler itself

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ConstantMemory<[T; N]> cannot be indexed at a runtime index: get() returns T by value, so the table is copied into the local depot

2 participants