Repository navigation
perf(mir-importer): materialize a bare array constant as one immutable global - #684
Merged
nihalpasham merged 2 commits intoAug 7, 2026
Merged
Conversation
…e global A `const TABLE: [T; N]` indexed by a runtime value was built element by element and stored into the local's stack slot, so every thread wrote its own copy of data the module image already carries: one `st.local` per element, then `ld.local` reads of thread-private memory. The identical data written `&[T; N]` has always become a single immutable device global read with one load, so the two spellings of one table cost wildly different amounts. Assign the constant with `mir.memcpy` from that same promoted global instead. The copy is what keeps this correct without new analysis: the local is ordinary mutable storage, and `opt` supplies the proof that removes the copy, rewriting the reads to the global wherever the local is never written (`isOnlyCopiedFromConstantMemory`). A whole-array *load* cannot reach the global however it is spelled, because LLVM splits every first-class-aggregate load and folds it straight back into per-element stores; only a memcpy survives to where that proof runs. For the exporter to write `constant` rather than `global` -- which is what makes reads of the storage invariant, and what selects `ld.global.nc` -- `MirGlobalAllocOp` carries a `global_immutable` marker through to `llvm::GlobalOp`. It is set only at the promoted-constant sites, never for a Rust `static`, whose bytes the host can still overwrite by symbol. It describes the storage, not a pointer: `MirPtrType::is_mutable` is deliberately not consulted, per NVIDIA#413. A write-once guard keeps the two lowerings from trading places. When the local *is* written the copy survives, and NVPTX expands a surviving memcpy into a byte loop -- worse than the element-wise stores it replaced -- so a local that is assigned more than once, borrowed, or written by a call keeps today's path. The guard only chooses between two correct lowerings, so an unrecognised write form costs performance, not correctness. Measured on an A10G (sm_86, driver 595.71.05), 8388608 threads x 64 divergent lookups per thread, 50 timed launches after 10 warmup, every kernel bit-correct against a host reference: entries spelling before after speedup 16 [f32; N] 1282.3us 374.3us 3.43x 256 [f32; N] 16044.1us 324.1us 49.50x 16 &[f32; N] 374.3us 374.2us 1.00x (control) 256 &[f32; N] 321.8us 324.1us 0.99x (control) `[f32; N]` now costs what `&[f32; N]` costs, to within 1%. PTX for the 256-entry kernel goes from 309 instructions with a 1 KiB local depot and 256 `st.local` to 70 instructions with no depot, and the table read becomes `ld.global.nc`. Adds `const_table_lookup`, which measures the three spellings of one table side by side and keeps their agreement checked. `ConstantMemory` is deliberately not addressed here and stays as the contrast: `get()` returns `T` by value, so a `ConstantMemory<[f32; N]>` copies all N entries out of `.const` into a local depot and still measures 3.46x / 49.53x, so `.const` cannot back a lookup table today. Refs NVIDIA#397. Signed-off-by: Vyncint Ng <[email protected]>
…and the written-copy fallback Three pieces of coverage layered on the lowering, none changing it: - llvm-export: a marked global must export as 'constant' and an unmarked one must stay 'global'. The keyword is the load-bearing bit of the whole design (it is what lets opt delete the copy and llc select ld.global.nc), and nothing asserted it textually. - mir-importer: emit_promoted_immutable_global marks the promoted global immutable and keys dedup by the full (type, bytes) image, so the same table reached twice shares one global and distinct byte images never alias. - const_table_lookup: a lut256_mut_copy kernel that writes its copy before reading it, with a bit-exact host reference. This checks the write-once guard's fallback end to end through real MIR: the memcpy path must not fire, the copy stays per-thread and element- materialized (262 .local lines in the PTX, vs 0 for lut256_value), and each thread's unique overwrite proves no cross-thread aliasing. Verified on an RTX 5090 (sm_120): all 7 kernels bit-correct, lut256_value at 1.00x of lut256_ref, .ll carries 'addrspace(1) constant' for both promoted tables.
Collaborator
|
Gist: This PR uses the established lowering for this problem:
I pushed one commit on top:
Verified on an RTX 5090 (sm_120):
Partially addresses #397 (the read-only by-value subcase; written scratch arrays and #399's iterator shapes stay open). |
nihalpasham
approved these changes
Aug 7, 2026
This was referenced Aug 7, 2026
nihalpasham
added a commit
to nh13/cuda-oxide
that referenced
this pull request
Aug 8, 2026
…m-export against NVIDIA#684's GLOBAL_IMMUTABLE_KEY additions)
7 of 8 tasks
nihalpasham
added a commit
that referenced
this pull request
Aug 8, 2026
…integer one (#694) * perf(mir-importer): promote a field-less enum array constant like an integer one #684 stopped bare array constants being built per thread, but its element gate admits only primitive scalars and nested arrays of those. A field-less enum array was left out, even though it holds nothing but discriminants and so is byte-identical to the `[u32; N]` of its values. It was still materialized into the per-thread local depot -- one `st.local` per element in every thread, for data the module image already carries -- and the lookup then read thread-private memory. There was no way to spell around it either: `&[Op; N]`, the reference form that works for scalar tables, is rejected outright. Replace the borrowed `&[T; N]` gate with a predicate of this path's own, which admits primitive scalars, field-less enums, and nested arrays of either. The byte image is rustc's evaluated allocation, so the discriminants were never the question; what the gate has to establish is that reading an element back is cheap, and for a field-less enum the whole element *is* its discriminant. Payload-carrying enums, tuples and structs stay out, and not because a byte image would be wrong. Projecting one field of a tuple element out of a local array copies the whole array to a fresh stack slot, once per field (#693). Those copies dominate: promoting a `[(u8, u32); 256]` table leaves its 925 PTX instructions, 4096-byte depot and 878 `st.local` exactly as they were and merely adds a 2 KiB global. Verified both ways on the A10G before excluding them. A size guard backs the widening: the copy is sized from the destination's converted type while the bytes come from rustc, so the two must agree before a byte image is trusted. `dialect_stored_size` answers from the `total_size` the storage builders reproduce, and any disagreement falls through to the element-wise path rather than copying over a differently-sized local. Measured on an A10G (sm_86, driver 595.71.05), 64 dependent divergent lookups per thread over 8388608 threads, 50 timed launches after 10 warmup. Every kernel bit-correct against a host reference in both runs, and each enum table is paired with a `[u32; N]` table over the same discriminants so the pair isolates the element type: entries table before after speedup u32 pair (control) 16 [Op; N] 1309.4us 361.4us 3.62x 361.4 -> 361.6us 256 [Op; N] 16073.3us 330.2us 48.68x 327.3 -> 330.0us An enum table now costs what the integer table of the same values costs, to within 1% at both sizes, and the controls did not move. PTX for the 256-entry enum kernel goes from 309 instructions with a 1 KiB depot and 256 `st.local` to 70 with no depot, reading through `ld.global.nc`. `array_constants`' `verify-code-shape.sh` pinned the enum array's `insertvalue` chain, so it now asserts the shape that replaced it: the discriminants in the read-only global's initializer, the copy out of that global, and the same runtime index and element load. Pinning the whole byte image in one pattern also fixes their order, which the previous per-discriminant search did not -- a permuted or truncated table now fails where before it passed. That example's runtime assertions were unaffected; the values were never in question. Adds `enum_table_lookup`, which measures both pairs and keeps their agreement checked. Closes #692. Signed-off-by: Vyncint Ng <[email protected]> * fix(mir-importer): admit a field-less enum table through its reference spelling The bare-array widening left the second defect of #692 open: the pointer path still checked elements with its own validator, so `const R: &[Op; N] = &OPS` kept hard-erroring with "invalid input program" while `OPS[i]` promoted cleanly. Route both promoted-constant paths through the one element gate. `validate_ptr_to_array_constant_type` now asks `promotable_array_element`, which absorbs the zero-length vacuous admission (`&[]` for any element type) so nothing the pointer path accepted is lost, and the two boundaries cannot drift apart again. The pointer path also gains the same byte-size agreement the bare-array promotion demands, except here disagreement is an input error because there is no element-wise lowering to fall back to. A unit test holds the reference form to the bare-array gate: field-less enum arrays pass, payload-carrying enums stay out, and the promoted empty-slice admission survives the rerouting. `enum_table_lookup` gains `enum256_ref_table`, which reads through `const R: &[Op; 256] = &OPS` against the same host reference. On an RTX 5090 it runs bit-correct at the bare enum table's exact cost (106.5us per launch, 1.21x the u32 control for both spellings), and the emitted IR shows it reading the same deduplicated immutable global the bare table copies from. --------- Signed-off-by: Vyncint Ng <[email protected]> Co-authored-by: nihalpasham <[email protected]>
nihalpasham
pushed a commit
that referenced
this pull request
Aug 8, 2026
…dex (#691) `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 #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 #690. Signed-off-by: Vyncint Ng <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Refs #397.
Summary
const TABLE: [T; N]indexed by a runtime value was built element by element andstored into the local's stack slot, so every thread wrote its own copy of data
the module image already carries: one
st.localper element, thenld.localreads of thread-private memory. The identical data written
&[T; N]has alwaysbecome a single immutable device global read with one load, so two spellings of
one table cost very different amounts.
This assigns the constant with
mir.memcpyfrom that same promoted global.Three parts:
mir-importer— a new arm in the existing "array initializers assigned toan addressable local" fast-path block emits
mir.global_alloc+mir.memcpyinstead of building the array as a value. The promoted-global emission is
factored out of
translate_ptr_to_array_constant, so both spellings now shareone code path and one content-keyed dedup.
dialect-mir/mir-lower/llvm-export—MirGlobalAllocOpcarries aglobal_immutablemarker through tollvm::GlobalOp, and the exporter writesLLVM
constantrather thanglobalfor it.Why a copy, and not the global's address
The local is ordinary mutable storage —
let mut t = TABLE; t[0] = x;is legal —so handing out the global's address would be wrong in general, and proving the
local is never written is exactly the analysis I wanted to avoid writing.
A
memcpyfromconstantstorage is unconditionally correct, andoptalreadysupplies that proof:
isOnlyCopiedFromConstantMemorydeletes the copy andrewrites the reads to the global wherever the local is never written, and keeps
the copy wherever it is.
That is also why the
constantkeyword is load-bearing rather than cosmetic. Itis what makes reads of the storage invariant, which both enables the elimination
and makes
llcselectld.global.nc(the read-only data cache).A whole-array load cannot reach the global however it is spelled. I probed
four shapes through
opt -passes='default<O2>'at LLVM 22.1.2 on the pinnedtoolchain, NVPTX triple, 256 x f32:
opt -O2alloca+insertvaluechain + aggregatestore(today)st.localsurviveconstantglobal + whole-arrayload+storeto alloca.fca.N.gep) and folds it back into per-element storesconstantglobal +llvm.memcpyinto allocagep @global; loadSo only a memcpy survives to where the proof runs. Plain external linkage is
enough — no
private/unnamed_addrneeded — which is why the exporter change isone keyword.
The marker is a property of storage, not of a pointer
global_immutableis set only at the promoted-constant sites, never for aRust
static, whose bytes the host can still overwrite by symbol(
ensure_static_global_allocis untouched).MirPtrType::is_mutableisdeliberately not consulted: a shared reference to a mutable static is an
immutable pointer to mutable storage, and #413 records that
is_mutablemust notbe read as a promise about the pointee. There is a test asserting lowering does
not infer immutability.
The write-once guard
Without it this trades one cost for another. When the local is written the
copy survives, and NVPTX expands a surviving
memcpyinto a byte loop —measurably worse than the element-wise stores it replaced. So
constant_local_is_written_oncerejects a local that is assigned more than once,borrowed at all (either mutability), or written by a call.
The guard only chooses between two correct lowerings — both give the local a
private copy — so an unrecognised write form costs performance, never
correctness. That is why its statement match ends in a catch-all rather than an
error.
Checked directly: a kernel doing
let mut t = TABLE; t[0] = input[i] as f32;still emits 64
st.local.b32with no memcpy loop, while the read-only kernelbeside it emits no depot and one
ld.global.nc.b32.Measured
A10G, from the evidence log's
nvidia-smiblock:8388608 threads x 64 divergent lookups per thread (536870912 lookups per launch),
50 timed launches after 10 warmup. Same kernels and same workload in both runs;
only the report's labels differ. Every kernel bit-correct against a host
reference in both.
Before (
.gpu-evidence/20260807T001402Z.log):After (
.gpu-evidence/20260807T012016Z.log):[f32; N][f32; N]&[f32; N]&[f32; N][f32; N]now costs what&[f32; N]costs, to within 1%, and the controls didnot move. PTX for the 256-entry kernel goes from 309 instructions with a 1 KiB
local depot and 256
st.localto 70 instructions with no depot, and thetable read becomes
ld.global.nc.Two entry counts are measured because
ptxascan rescue a small table on itsown. Worth flagging:
ptxas -vreported "0 bytes stack frame" for every one ofthese kernels, before and after — it is not a usable signal for this, and only
the runtime measurement exposed it.
How this differs from #398 and #636
Both were closed for good reasons that this does not reproduce.
measured 16-19% slower on the workload it targeted. The dominant cost here
is the initialization — N stores per thread against K reads — which select
chains do not touch. That is also why the small-table case only moves 3.4x
while the 256-entry case moves 49.5x: the cost is linear in N.
gemm_sol's PTX grew ~64%. This shrinksPTX (309 -> 70 on the affected kernel) and adds no pipeline stage: no extra
optrun, no unroller, no env plumbing. Kernels that never materialize anarray constant are untouched.
already builds, and the elimination is
opt's own existing pass.I have not tried to close #397 with this — the iterator-adapter half (#399) and
mutable local scratch arrays are untouched, and the guard deliberately declines
anything it cannot see is write-once.
Also here, deliberately unfixed
ConstantMemory::get()returnsTby value, so aConstantMemory<[f32; N]>reads all N entries out of
.constand writes them into a local depot. It stillmeasures 3.46x / 49.53x off the other two spellings, so
.constcannot back alookup table today. This is a separate defect in
cuda-device's API shape ratherthan in lowering, so I left it alone and kept it in the example as the contrast.
Happy to file it separately if useful.
New example
const_table_lookupmeasures the three spellings of one table side by side andkeeps their agreement checked. The index comes from a per-thread LCG so it is
unpredictable and lane-divergent, and the kernel is lookup-bound rather than
bandwidth-bound (4 bytes in, 4 bytes out per thread). All six kernels verify
bit-exactly against a host reference computed with the same add order.
Validation
Local (
fmt,clippy, unit tests, docs, doctests all clean):On the A10G:
.gpu-evidence/20260807T005028Z.log)(
.gpu-evidence/20260807T012016Z.log), coveringarray_constants,array_index,array_init,enum_array_match,cast_tests,tuple_array_provenance,tuple_constant_provenance,uninit_const,device_global,constant_memory_coeffs,place_read_fallbacks,ref_index_projections, plusvecadd/vectorizationas passing controlsand
tma_copyas a skip controlarray_constantsis the existing regression test for array-constant values, soit is the one that matters most here; it passes in both runs.
New test:
immutable_marking_survives_lowering_and_is_not_assumedasserts themarker survives MIR -> LLVM lowering and that a plain static does not acquire
it.
Not verified: SASS.
nvdisasmis not on the image I used, so theinstruction-level evidence above is PTX only.