Repository navigation
feat(intrinsics): add ex2 approximate f16 - #1104
Merged
Merged
Conversation
This was referenced Aug 22, 2026
nihalpasham
force-pushed
the
ex2-approx-f16
branch
from
August 23, 2026 04:58
04932ae to
2a78c2f
Compare
Collaborator
|
Signed-off-by: Sam, Joochul Chang <[email protected]>
nihalpasham
force-pushed
the
ex2-approx-f16
branch
from
August 23, 2026 06:44
2a78c2f to
1e9fa2e
Compare
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
force-pushed
the
ex2-approx-f16
branch
from
August 23, 2026 06:51
1e9fa2e to
de4b54d
Compare
nihalpasham
approved these changes
Aug 23, 2026
nihalpasham
left a comment
Collaborator
There was a problem hiding this comment.
- The concrete benefit is native
ex2.approx.f16coverage 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
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]>
This was referenced Aug 28, 2026
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.
Summary
Add catalog-owned
ex2.approx.f16as ABI entryi1016, using the existing scalar-f16u16API /i16dialect carriers, with a GPU validation example.PTX documents a PTX 7.0 / sm_75 floor. Pinned LLVM 22 selects
llvm.nvvm.ex2.approx.f16atsm_75 +ptx70and rejects sm_70 / PTX 6.5. LLVM 22 also rejects.ftz.f16;.ftz.bf16is a separate PTX 7.8 / sm_90 variant.Evidence
The LLVM route emits
ex2.approx.f16at 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 containsMUFU.EX2.F16. A per-variantlibnvvm_evidence_profileselects 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_0exports. That binding fix is not included here and should merge first.Example and validation
examples/ex2_approx_f16launches 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: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:
The listed local checks passed; the full all-example compile and clippy lanes need CI's CUDA 13 toolchain.
Maintainer repair
sm_75with PTX 7.0 end to end.ptxasrebuilt the exact recorded 640-byte PTX into a 1,464-byte cubin.This supersedes the earlier selected-target evidence details above.