Repository navigation
feat(cuda-device): let a ConstantMemory table be read at a runtime index - #691
Conversation
`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]>
|
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 This PR's execution evidence remains its own scoped run, 9/9 |
|
Gist: Not a compiler change, just the missing safe accessor.
Verified on an RTX 5090 (sm_120):
Closes #690. Merging. |
Closes #690.
Summary
ConstantMemory<T>had one accessor,get, returningTby value. Right fora scalar, but it left no way to index a
ConstantMemory<[T; N]>at a runtimeindex: a value has no address, so the copy is spilled to the thread's local depot
— one
st.localper element in every thread — and the lookup then readsthread-private memory.
#[constant]could not express the shape constant memoryexists for:
This adds
get_ref(&self) -> &T, which borrows the storage so the index stays inconstant space.
No codegen change. A reference into a
#[constant]static already keepsaddress space 4 all the way down: the symbol stays
addrspace(4) globalin LLVMIR (so a host
set_<name>remains visible) and the read emits oneld.const.b32. Only the safe way to obtain that reference was missing. For thereproducer 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_coeffsdoesc[0],c[1];constant_memorydestructures
let [c0, c1, c2, c3] = COEFFS.get();. SROA cleans those upentirely. Only a runtime index falls off the cliff, so both keep using
gethereand both still pass.
Safety
Safe under the contract
getalready relies on: device code only reads thisstorage, so no
&mutexists to alias it, and the host writes only between kernellaunches via
cuMemcpyHtoD, synchronized out-of-band relative to deviceexecution. Holding a shared reference for the duration of a launch observes no
write that
getwould not.Borrowing through the
UnsafeCellis what keeps this honest: the storage staysmutable 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 isthe property the wrapper exists for, and the emitted
ld.const.b32confirms itsurvives.
Measured
A10G, from the evidence log's
nvidia-smiblock:256-entry
f32table, 64 dependent lookups per thread over 8388608 threads, 50timed launches after 10 warmup. Every variant bit-identical against a host
reference computed with the same add order:
get()get_ref()Note the
get()row barely moves between the two index patterns (16048 vs16065): the per-thread depot copy dominates so completely that the access pattern
stops mattering. That is the signature of the defect.
The second half:
.constis not simply faster memoryThe 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:
.const(get_ref).global(const [f32; N]).const, 1.25x.global, 23.7xOn 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], whichsince #684 is materialized as one immutable device global read with
ld.global.nc— no host upload and no#[constant]at all. Choosing.constbythe 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: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_refinstead. The module-level docs gained the two-accessordistinction, and the module example uses
get_ref.New example
constant_memory_tablemeasures all six combinations of {get,get_ref,const [f32; N]} x {divergent, warp-uniform} and checks each against its ownhost 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
_unikernels seed frominput[i & !(WARP - 1)]— one warp-uniform load — soonly the index's divergence varies, not the memory traffic or the arithmetic
count.
Validation
Local, all clean:
On the A10G — scoped smoketest 9/9, 0 fail (
.gpu-evidence/20260807T134040Z.log),covering every constant-memory example plus controls:
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.
nvdisasmis not on the image I used, so theinstruction-level evidence here is PTX only.
Not in this PR
impl Index for ConstantMemory<[T; N]>would read better at the call site thanget_ref()[i], but it only helps arrays whileget_refalso covers structs. Gladto add it on top if you prefer that spelling.