Skip to content

feat(intrinsics): add ex2 approximate f16 - #1104

Merged
nihalpasham merged 2 commits into
NVIDIA:mainfrom
almightychang:ex2-approx-f16
Aug 23, 2026
Merged

nihalpasham merged 2 commits into
NVIDIA:mainfrom
almightychang:ex2-approx-f16

Conversation

@almightychang

@almightychang almightychang commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add catalog-owned ex2.approx.f16 as ABI entry i1016, using the existing scalar-f16 u16 API / i16 dialect carriers, with a GPU validation example.

PTX documents a PTX 7.0 / sm_75 floor. Pinned LLVM 22 selects llvm.nvvm.ex2.approx.f16 at sm_75 +ptx70 and rejects sm_70 / PTX 6.5. LLVM 22 also rejects .ftz.f16; .ftz.bf16 is a separate PTX 7.8 / sm_90 variant.

Evidence

The LLVM route emits ex2.approx.f16 at the floor. The libNVVM route uses a dedicated CUDA 12.0 evidence profile, following #946 because CUDA 13.3 was unavailable on the measurement host. CUDA 12 libNVVM produced LTOIR that cuda-oxide linked into the recorded 4,264-byte sm_75 cubin (4fd44330...bfe); disassembly contains MUFU.EX2.F16. A per-variant libnvvm_evidence_profile selects that profile only for this record; the other 40 scalar-math variants retain the family default and every variant still resolves exactly two routes.

Dependency

Depends on #1103, which lets the materializer load Debian CUDA 12's __nvJitLink*_12_0 exports. That binding fix is not included here and should merge first.

Example and validation

examples/ex2_approx_f16 launches the intrinsic and checks six inputs, including a result in the binary16 subnormal range, against the PTX maximum relative-error bound of 2^-9.9. On an RTX 5080 (sm_120) it produced:

input=0x0000 output=0x3c00 expected=0x3c00
input=0x3c00 output=0x4000 expected=0x4000
input=0xbc00 output=0x3800 expected=0x3800
input=0x4000 output=0x4400 expected=0x4400
input=0x3800 output=0x3da8 expected=0x3da8
input=0xcb80 output=0x0200 expected=0x0200
PASS: ex2.approx.f16 results are within the PTX 2^-9.9 relative-error bound

For GPUs below sm_75, smoketest builds device code for sm_75 and lets the example's host capability check skip before module loading.

Validation performed:

cargo run -p cuda-intrinsics-gen -- check
cargo run -p cuda-intrinsics-gen -- probe --all --skip-terminal
cargo run -p cuda-intrinsics-gen -- check-abi-history --base-ref origin/main
cargo test -p cuda-intrinsics-gen
cargo clippy --workspace --all-targets -- -D warnings
cargo clippy --manifest-path crates/rustc-codegen-cuda/examples/ex2_approx_f16/Cargo.toml --all-targets -- -D warnings
cargo fmt --all -- --check
cargo fmt --manifest-path crates/rustc-codegen-cuda/examples/ex2_approx_f16/Cargo.toml -- --check
scripts/check-example-smoketest-contract.sh
scripts/check-test-matrix-coverage.sh
scripts/check-spdx-headers.sh
CUDA_TOOLKIT_PATH=/usr cargo oxide run ex2_approx_f16

The listed local checks passed; the full all-example compile and clippy lanes need CI's CUDA 13 toolchain.

Maintainer repair

  • The selected LLVM and terminal route now uses sm_75 with PTX 7.0 end to end.
  • CUDA 13.3 ptxas rebuilt the exact recorded 640-byte PTX into a 1,464-byte cubin.
  • Both lowering backends have direct contract and rejection tests.
  • Generator, ABI, dialect, lowering, clippy, assembly, and floor-mutation checks pass.

This supersedes the earlier selected-target evidence details above.

@nihalpasham nihalpasham added enhancement New feature or request intrinsics Device intrinsics and libdevice math mappings device-apis User-facing device-side and kernel-authoring APIs (cuda-device, cuda-macros) Depends Blocked on another PR/issue or an upstream dependency labels Aug 23, 2026
@nihalpasham

nihalpasham commented Aug 23, 2026 •

Copy link
Copy Markdown
Collaborator
  • Benefit: kernels get typed access to native ex2.approx.f16 without handwritten inline PTX or an f32 promotion/conversion path. This is API coverage and usability, not a measured performance or safety claim.
  • The original evidence selected sm_80 but assembled for sm_75, which CUDA 13.3 rejected. I layered one commit that uses PTX 7.0 / sm_75 end to end and adds direct LLVM-NVPTX and libNVVM lowering and rejection tests.
  • Generator, ABI, lowering, assembly, and floor-mutation checks pass. Hosted CI is queued and waiting for explicit fork-run approval; runtime evidence remains the contributor's RTX 5080 run.
  • fix(nvjitlink): resolve versioned toolkit symbols #1103 must merge first. No issue closes on merge.

@nihalpasham nihalpasham added codegen Device code-generation pipeline (Rust MIR to IR to PTX) tests Adds or improves test coverage IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) cuda-feature A CUDA hardware/toolkit feature (TMA, tcgen05, WGMMA) examples Example kernels and host harnesses under crates/rustc-codegen-cuda/examples labels Aug 23, 2026
Align selected LLVM and terminal evidence on sm_75 with PTX 7.0, validate both lowering backends directly, and reject invalid f16 transport and format combinations.

Signed-off-by: nihalp <[email protected]>
@nihalpasham nihalpasham removed the Depends Blocked on another PR/issue or an upstream dependency label Aug 23, 2026

@nihalpasham nihalpasham 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.

  • The concrete benefit is native ex2.approx.f16 coverage through both lowering backends while preserving the 16-bit ABI and the PTX 7.0 / sm_75 gate.
  • LLVM/PTX evidence and negative transport, format, and generated-source checks cover the new path.
  • All seven workflows pass on exact head de4b54d1; both commits have valid signatures and DCO trailers.

@nihalpasham
nihalpasham merged commit 1f6a0fd into NVIDIA:main Aug 23, 2026
51 checks passed
nihalpasham added a commit that referenced this pull request Aug 28, 2026
…1186)

* feat(mir): preserve Rust pointer and reference kind

Signed-off-by: Raul Estrada <[email protected]>

* refactor(mir-importer): delete dead get_thread_local dispatch, document Erased tail slices

DisjointSlice::get_thread_local is not declared anywhere in cuda-device,
so both dispatch arms and the emitter were unreachable. The emitter also
built its *mut T result through the kind-erased constructor and stored
it into a rustc-typed destination, which the new kind-aware verification
would reject if the path ever became reachable.

The three DST-tail reconstruction sites keep MirSliceType::get on
purpose; comments now state the invariant (projection-internal values
stay Erased until an Rvalue::Ref/AddressOf boundary retypes them).

Signed-off-by: nihalpasham <[email protected]>

* fix(mir): implement the intrinsic-call boundary for pointer kinds

Three example kernels exposed two gaps in the kind-preservation
policy this PR documents:

1. Intrinsic results were stored with the normalization-only path, so
   an emitter-internal Erased pointer result could not take the
   destination slot's rustc-declared kind and MirStoreOp verification
   failed (mathdx_ffi_test: *mut i8 in AS3, mcast_barrier_test:
   *const u64 in AS7). A compiler-recognized device operation is one
   of the documented Rust-typed boundaries, so
   emit_store_result_and_goto now stores through
   store_local_at_rust_boundary, which establishes the declared kind
   while still requiring the same pointee shape.

2. The Rvalue::Ref boundary now emits a kind-only mir.cast <PtrToPtr>
   between wgmma_fence and the MMA, which the deferred-accumulator
   region matchers treated as an unsupported op, so fusion silently
   declined and lowering failed (wgmma_mma_bf16). Kind-only retypes
   between thin pointers with the same pointee and address space lower
   to nothing, so both the linear/pipeline walker and the counted-loop
   whitelist now look through them.

Signed-off-by: nihalpasham <[email protected]>

* fix(mir): enforce pointer-kind authority end to end

Verify exact Rust and ABI call boundaries, including closure receivers and drop glue, and make pointer-producing casts, projections, aggregates, intrinsics, and storage operations preserve or explicitly establish their authority.

Close aggregate and canonical-function-token laundering paths, preserve raw kinds through NVVM cluster mapping, and run whole-tree producer checks before pointer kinds are erased.

Canonicalize harmless pointer-kind reborrows in deferred WGMMA accumulator matching, with counted-loop, verifier-negative, and real Rust pipeline coverage.

Signed-off-by: nihalpasham <[email protected]>

* fix(mir): close pointer-kind integration gaps

Signed-off-by: nihalpasham <[email protected]>

* fix(lower): size ptr_offset elements from the op's result type

A kind-only mir.cast lowers to a plain value forwarding with no LLVM
instruction. convert_ptr_offset derived the GEP element type from the
pointer operand's recorded type history, which does not follow that
replacement edge, and on a miss silently fell back to a byte-sized
element. wrapping_offset on *const i32 then stepped back N bytes
instead of N elements and the kernel faulted with a misaligned
address at run time (ptr_offset_from example, CUDA error 716).

Take the element type from the mir.ptr_offset result type instead,
which still carries the exact MIR pointee when the converter runs,
and make a missing pointer fact a hard compile error rather than a
guessed i8.

Signed-off-by: nihalpasham <[email protected]>

* fix(lower): derive pointer facts from op-carried types, not operand history

Four converters derived semantic facts (element size, aggregate layout,
enum layout) by walking the pointer operand's recorded type history.
That history does not follow the value forwarding a kind-only mir.cast
lowers to, so a miss produced a spurious error, and a stale hit could
silently misscale a GEP stride, write an enum tag at the wrong offset,
or multiply a memcpy byte count.

Each fact now rides the op itself:

- mir.array_element_addr: element type from the op's own result type;
  single-index GEP over the element (same address as the old
  two-index [N x T] form).
- mir.memcpy / mir.memmove: new memcpy_elem_type / memmove_elem_type
  TypeAttr stamped by typed build() constructors from dst's build-time
  pointer type; verifiers require it to equal the dst/src pointee.
- mir.set_discriminant: new set_discriminant_enum_ty TypeAttr, same
  treatment.
- mir.field_addr: new aggregate_ty TypeAttr plus a build() constructor;
  every importer construction site goes through it.

A missing fact is now a hard compile error, never a guessed i8 or a
stale history hit. Attribute keys are op-prefixed because pliron
registers attribute dictionary keys globally.

Validated: 216/216 examples compile and run on sm_120a, gemm_views
bench at parity (safe == raw bitwise), workspace suites, fmt, clippy.

Signed-off-by: nihalpasham <[email protected]>

* fix(importer): read enum discriminants from typed constants

Enum discriminants were scraped out of format!("{:?}") Debug output
with silent defaults on a miss. The worst consumer was the atomic
memory-ordering decoder: an ordering constant whose Debug string did
not parse became discriminant 0, which is Relaxed, silently deleting
the fences the source asked for.

- extract_enum_variant reads the tag with Allocation::read_uint (hard
  error on unreadable or uninitialized bytes; the old byte-OR loop
  invented values from partial data), allows ZeroSized only for
  single-variant enums, rejects Unevaluated/Param, and maps the tag to
  a variant through AdtDef::discriminant_for_variant, masked to the
  stored tag width.
- extract_ordering matches the variant by NAME, so a cuda-device
  renumber cannot silently remap orderings, and every unknown case is
  a hard compile error. The Relaxed and SeqCst fallbacks are gone.

Validated: workspace suites, 216/216 examples compile and run on
sm_120a (atomics and scoped_atomic_load_store execute correctly),
gemm_views bench at parity, fmt, clippy.

Signed-off-by: nihalpasham <[email protected]>

* fix(importer): evaluate shared-memory const generics with typed reads

SharedArray's N and ALIGN const generics were decoded by scraping the
TyConst Debug string, and unparseable consts were silently dropped
from the list before positional indexing, so a failed N parse let
ALIGN be read as the element count: an undersized shared-memory
allocation. DynamicSharedArray's ALIGN defaulted to 16 on every read
failure, silently misaligning extern shared memory declared with a
larger alignment (a runtime TMA hazard).

- N and ALIGN now come from TyConst::eval_target_usize at their exact
  declaration positions; any non-evaluable const is a hard error, and
  ALIGN defaults only when the parameter is genuinely absent.
- The two SharedArray substs checks (call classification and intrinsic
  dispatch) share one typed predicate: Self at position 0, ADT named
  SharedArray, defined in the cuda_device crate. Debug-string
  contains() matching is gone from both, so a user type named
  SharedArray can no longer be classified as shared memory here.
- DynamicSharedArray dispatch is anchored to the cuda_device crate and
  its ALIGN read hard-errors instead of assuming 16.

Validated: workspace suites, 216/216 examples compile and run on
sm_120a (dynamic_smem, addressof_sharedarray, swizzle_smem,
compiler_features execute correctly), gemm_views bench at parity,
fmt, clippy.

Signed-off-by: nihalpasham <[email protected]>

* fix(importer): read constant values from allocations, not Debug strings

Integer and raw-pointer constant values were recovered by substring
parsing of format!("{:?}") output. A parse miss produced 0 (a null
pointer or a zero integer), and the pointer parser COMPACTED
partially-uninitialized bytes, so bytes [None, Some(1)] decoded as
address 1: a wrong address, not even a default.

- Raw-pointer constants: read exactly target_pointer_width bytes from
  the backing allocation with Allocation::read_partial_uint; hard
  error when the allocation is missing, short, or uninitialized, and
  a debug_assert that provenance-carrying constants took their own
  branch earlier.
- Integer constants: the ASCII-digit fallback is deleted; the value
  comes from the allocation with the same uninitialized-byte and
  provenance hard errors (the old helper zero-filled uninit bytes, so
  its error path alone could not catch them).
- format!("{:?}") on constants survives only as diagnostics text.

Validated: workspace suites, 216/216 examples compile and run on
sm_120a (option_ref_transmute, transmute_scalar_struct, cast_tests,
checked_arith execute correctly), gemm_views bench at parity, fmt,
clippy.

Signed-off-by: nihalpasham <[email protected]>

* fix(importer): resolve trait projections by lang-item DefId

Fn/FnMut/FnOnce Output and Index/IndexMut Output projections were
detected by substring-matching the DefId Debug string, so any user
trait whose path contained Fn+Output (or Index+Output) silently
resolved to the wrong type. Closure and fn-item struct names embedded
the Debug id field, which depends on first-touch order, making type
names nondeterministic across compilations.

- The driver resolves FnOnceOutput, Index, and IndexMut once inside
  rustc_internal::run and hands them to the importer as KnownDefs;
  the importer stores them in a per-run cell that is overwritten at
  every pipeline entry so stale ids cannot leak.
- One FnOnceOutput DefId equality replaces all three Fn-trait
  substring tests (Output lives only on FnOnce); Index/IndexMut
  resolve via DefId::parent(). Non-matches fall through to the
  existing hard error, never a guess.
- The SharedArray projection arm gains the cuda_device crate anchor.
- Closure and fn-item type names come from CrateDef::name(), stable
  across runs.

Validated: workspace suites, 216/216 examples compile and run on
sm_120a (device_closures, unchecked_indexing, addressof_sharedarray,
vecadd execute correctly), gemm_views bench at parity, fmt, clippy.

Signed-off-by: nihalpasham <[email protected]>

* fix(importer): anchor name-matched identities to their defining crates

Seven cuda-device types (SharedArray, Barrier, DisjointSlice,
ThreadIndex, TmaDescriptor, RangeToken, ConstantMemory) were
recognized by bare trimmed_name() comparison, so a user struct with
the same name was silently mistranslated (a user ThreadIndex became a
bare usize; a user SharedArray became shared memory). The
bounds-check call deleter matched any function whose path merely
CONTAINED precondition_check, so a user fn named my_precondition_check
was silently deleted from the kernel.

- One helper, is_cuda_device_adt, carries the name + defining-crate
  check; every ADT identity site routes through it. A non-match falls
  through to ordinary handling, never an error.
- The compiler-marker fns (__cluster_config, __dynamic_shared_alignment)
  gained the same crate anchor.
- Call deletion is now is_std_precondition_check: defining crate must
  be core or alloc (alloc's Vec expands the same macro and those shim
  bodies are intentionally not collected) AND the exact last path
  segment must be precondition_check. User functions translate as
  normal calls.

Validated: workspace suites, 216/216 examples compile and run on
sm_120a (slice_index_bounds_check still traps out-of-bounds and
unchecked_indexing still elides, proving the anchored deletion fires
for core's shims), gemm_views bench at parity, fmt, clippy.

Signed-off-by: nihalpasham <[email protected]>

* fix(lower,export): make byte sizes and alignments exact or absent

Two helpers ended in a literal 8. get_type_size summed struct fields
with no padding and answered 8 for anything unknown, and that number
became real memcpy byte counts and layout offsets. natural_alignment
emitted 'align 8' for unknown types and non-power-of-two values like
'align 3' for odd integer widths (invalid LLVM IR).

- get_type_size is deleted. memcpy/memmove sizes come from the rustc
  stride of the stamped MIR element type, then exact LLVM layout, else
  a hard error naming the type. The relocation storage check and the
  struct-slot-map offset advance use the exact helpers with an
  explicit refusal instead of a guess.
- natural_alignment returns Option: None for unknown types, any
  non-power-of-two, and integers wider than i128 (the old code
  over-claimed there too). Loads, stores, and allocas omit the align
  attribute on None, which LLVM soundly reads as the type's ABI
  alignment. Atomic load/store, where the syntax mandates alignment,
  hard-error instead of guessing.

Validated: workspace suites, 216/216 examples compile and run on
sm_120a; vectorization's per-type table is byte-identical, so
LoadStoreVectorizer behavior is unchanged; regenerated .ll files show
zero newly-omitted align attributes in practice; gemm_views bench at
parity; fmt, clippy.

Signed-off-by: nihalpasham <[email protected]>

* test(examples): cover without_provenance pointer constants

Adds ptr_without_provenance: a minimal example minting non-null
integer-address pointer constants (ptr::without_provenance), the path
where the retired Debug-string parser could compact partially
initialized bytes into a wrong address. The .ll shows the exact
inttoptr constants under test.

Also adapts the ex2 negative lowering test (landed on main in #1104)
to the messages that surface on this branch: the generated op
verifier rejects malformed scalar-math ops before the lowering
recipe check runs.

Signed-off-by: nihalpasham <[email protected]>

* refactor(importer): gather the typed fact readers into facts.rs

Pure move, zero behavior change. Every helper whose job is reading a
fact from rustc through typed APIs now lives in one module,
translator/facts.rs, with the oracle contract in its doc:

  rustc (typed APIs) ──► facts.rs ──► the rest of the importer
  a fact is exact, or it is a hard error; never a guess, never a
  Debug string. New rustc questions go here, nowhere else.

Gathered: KnownDefs and its per-run cell, is_cuda_device_adt,
is_cuda_device_fn, is_std_precondition_check, self_ty_is_shared_array,
eval_usize_const (shared extraction of the SharedArray and
DynamicSharedArray const-generic readers, error strings unchanged),
extract_enum_variant. Translation machinery that merely consumes the
facts stays where it was.

Validated: full workspace suites, 218/218 examples compile and run on
sm_120a, gemm_views bench at parity, fmt, clippy.

Signed-off-by: nihalpasham <[email protected]>

* feat(importer): couple pointer-kind minting to oracle evidence

A concrete pointer kind (SharedRef, UniqueRef, RawConst, RawMut) can
now only be minted by presenting a PointerOrigin, a fact value with
private fields that facts.rs alone can construct, from one of:

  rustc evidence                    named ABI rules (documented)
    Ty (Ref/RawPtr)   ─┐             DynamicSharedArray result = RawMut
    BorrowKind        ─┼► PointerOrigin ◄─ DisjointSlice data = RawMut
    RawPtrKind        ─┤       │
    carrier kind      ─┘       ▼  (propagate, never strengthen)
                          mint_* helpers = the only kinded-type path

A new root clippy.toml bans the raw kind constructors everywhere
else (CI runs clippy with -D warnings, so a future direct mint is a
build error pointing at PointerOrigin). The two previously hardcoded
RawMut literals became the named ABI-rule constructors. Dialect-side
one-way verifiers from the kind model remain the runtime backstop.

Pure coupling refactor: regenerated vecadd and dynamic_smem .ll are
byte-identical to before the change.

Validated: workspace suites, clippy across both workspaces, 218/218
examples compile and run on sm_120a, gemm_views bench at parity, fmt.

Signed-off-by: nihalpasham <[email protected]>

---------

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

Labels

codegen Device code-generation pipeline (Rust MIR to IR to PTX) cuda-feature A CUDA hardware/toolkit feature (TMA, tcgen05, WGMMA) device-apis User-facing device-side and kernel-authoring APIs (cuda-device, cuda-macros) enhancement New feature or request examples Example kernels and host harnesses under crates/rustc-codegen-cuda/examples intrinsics Device intrinsics and libdevice math mappings IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) tests Adds or improves test coverage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants