Skip to content

feat: add scalar f16 and bf16 min/max intrinsics - #649

Merged
nihalpasham merged 3 commits into
NVIDIA:mainfrom
honeyspoon:feat/scalar-half-minmax
Aug 4, 2026
Merged

nihalpasham merged 3 commits into
NVIDIA:mainfrom
honeyspoon:feat/scalar-half-minmax

Conversation

@honeyspoon

@honeyspoon honeyspoon commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Overlap with the f16 primitive

Stating this up front: 8 of the 24 are reachable from safe Rust today on nightly
with #![feature(f16)], because LLVM lowers the generic min/max intrinsics
straight to these instructions:

Rust LLVM PTX
a.min(b) / a.max(b) llvm.minnum.{f16,bf16} min.f16 / max.f16
a.minimum(b) / a.maximum(b) llvm.minimum.{f16,bf16} min.NaN.f16 / max.NaN.f16

Verified on the pinned llc at sm_80 +ptx70. So the 4 plain and 4 NaN forms
duplicate instructions the language already emits; the remaining 16 have no
Rust spelling
- every ftz form and every xorsign.abs form.

Two reasons to keep the overlapping 8 rather than trim to 16:

  • The intrinsic pins the exact instruction. a.min(b) routes through
    llvm.minnum, which the optimizer is free to fold, reassociate under
    fast-math, or select differently; the generated stub is a guarantee.
  • It matches how the family already works. min_f16x2 / max_f16x2 live in
    packed_alu even though llvm.minnum.v2f16 reaches min.f16x2 generically,
    and float:: exposes explicit-rounding arithmetic alongside plain + and *.

Happy to drop the 8 if you would rather the surface stay minimal.

Completes the extended_minmax family with the scalar 16-bit forms. The family already covered f32, f16x2, and bf16x2; LLVM also declares the one-element f16 and bf16 variants, and every form admitted here lowers on the pinned backend.

What this adds

24 intrinsics:

Format Forms Floor
f16 all 8 modifier combinations of min/max over ftz, NaN, xorsign.abs sm_80/PTX 7.0, or sm_86/PTX 7.2 with xorsign.abs
bf16 the 4 combinations without ftz same

What it deliberately excludes

The four bf16 ftz declarations. LLVM declares llvm.nvvm.fmin.ftz.bf16 and its relatives, but the NVPTX backend has no selection pattern for them:

LLVM ERROR: Cannot select: intrinsic %llvm.nvvm.fmin.ftz.bf16

They also carry no tablegen selection record in intrinsics/imported.json, which is the same signal from the other direction. The exclusion is recorded in canonical_extended_minmax_variants and in the cuda_device::bf16 module docs so it is not mistaken for an oversight.

Carrier

A scalar half rides as its u16 bit pattern (i16 in the dialect) - the convention packed_conversion already uses for e4m3x2 and e5m2x2 operands - and inline PTX uses the 16-bit h register class.

The lowering helper's packed: bool becomes a three-state MinMaxCarrier, so f32, scalar halves, and packed pairs each select their own register class instead of two of them sharing one boolean.

ABI ids

The new variants continue at i0830, not i0578: the ids directly after this family's original block were reserved by other families before the family grew. extended_minmax_abi_id makes the discontinuity explicit, and the admission test pins both block boundaries (i0577 -> i0830).

Naming

min.f16 and min.bf16 carry no modifier at all, so the identifier, source record, LLVM symbol, and selection record are now built by joining the parts that are present rather than by a format string with fixed separators. The construction is unchanged for all 28 pre-existing variants - the admission test still pins min_ftz_f16x2/i0550 first and max_xorsign_abs_f16x2/i0577 at index 27.

Evidence

Measured, not asserted. Two new fixtures per backend profile:

  • Pinned LLVM 22.1.2: all 24 typed declarations canonicalize under llvm-as/llvm-dis, lower to their exact instruction heads, and assemble under CUDA 13.3 ptxas. The inline-PTX route produces a byte-identical cubin to the typed route in each target tier.
  • CUDA 13.3 libNVVM: the same forms compile to PTX 9.3, assemble to a cubin byte-identical to the pinned-LLVM one, and survive -gen-lto plus nvJitLink.

Hardware verification

The generated_intrinsics example gained two things:

  1. All 24 intrinsics in the existing compile_extended_minmax coverage kernel, so they are driven through device codegen and libNVVM verification. This is the check that catches a stale generated_intrinsic_targets.rs.
  2. A launched scalar_half_minmax kernel with bit-exact host assertions, run on an sm_86 RTX A2000. Inputs +1.0 and -2.0 are asymmetric and opposite-signed so the xorsign.abs forms cannot pass by accident; a second launch with a NaN operand separates the plain forms from the NaN forms.

That test corrected an assumption: PTX's canonical NaN is 0x7FFF - all-ones exponent and mantissa with a clear sign, the 16-bit analogue of the 0x7fffffff the ISA specifies for f32 - not the IEEE default quiet NaN (0x7E00 for f16, 0x7FC0 for bf16). The measured value is pinned in the test and documented in both modules.

Verification

Rebased on a77daf85; 2 commits, both DCO signed off.

  • cargo run -p cuda-intrinsics-gen -- check - clean
  • probe --all --skip-terminal - 853/853 routes; each of the 24 new ones lowers to its expected instruction
  • check-abi-history --base-ref upstream/main - 829 base entries preserved, 853 total
  • cargo fmt --all -- --check - clean in all three workspaces
  • cargo clippy --workspace --all-targets -- -D warnings - clean
  • RUSTDOCFLAGS='-D warnings' cargo doc - clean
  • Tests: cuda-intrinsics-gen 288, cuda-intrinsics 853, mir-importer 918, mir-lower 245, dialect-nvvm 50
  • scripts/smoketest.sh -o '^generated_intrinsics$' - passes --compile-only (verified by libNVVM) and launched on hardware

Full CI is green on the fork PR (50/50 checks, including compile all examples): honeyspoon#115

Note on scope

There is no tracking-issue box for these forms - #274 covered the packed min/max.f16x2 variants and is fully checked off. Happy to file an issue first if you would rather the design be agreed before review.

https://claude.ai/code/session_01LXYptgNnAcDSbkgyWGYQzk

Completes the `extended_minmax` family with the scalar 16-bit forms. The
family already covered `f32`, `f16x2`, and `bf16x2`; LLVM also declares the
one-element `f16` and `bf16` variants, and every form admitted here lowers
on the pinned backend.

Adds 24 intrinsics:

- `f16`: all eight modifier combinations of `min`/`max` over `ftz`, `NaN`,
  and `xorsign.abs`.
- `bf16`: the four combinations that do not request `ftz`.

The four `bf16` `ftz` declarations are deliberately excluded. LLVM declares
`llvm.nvvm.fmin.ftz.bf16` and its relatives, but the NVPTX backend has no
selection pattern for them: instruction selection fails with `Cannot select:
intrinsic %llvm.nvvm.fmin.ftz.bf16`. They also carry no tablegen selection
record in the imported ledger, which is the same signal. This is recorded in
`canonical_extended_minmax_variants` and in the `cuda_device::bf16` module
docs so the gap is not mistaken for an oversight.

Carrier: a scalar half rides as its `u16` bit pattern (`i16` in the dialect),
which is how `packed_conversion` already carries `e4m3x2` and `e5m2x2`
operands, and inline PTX uses the 16-bit `h` register class. The lowering
helper's `packed: bool` becomes a three-state `MinMaxCarrier` so `f32`,
scalar halves, and packed pairs each select their own register class instead
of two of them sharing one boolean.

ABI ids continue at i0830 rather than i0578, because the ids directly after
the family's original block were reserved by other families before this
family grew. `extended_minmax_abi_id` makes that discontinuity explicit and
the admission test pins both block boundaries.

Naming had to become separator-aware: `min.f16` and `min.bf16` carry no
modifier at all, so the identifier, source record, LLVM symbol, and
selection record are now built by joining the parts that are present. The
construction is unchanged for all 28 pre-existing variants.

Evidence: two new fixtures per backend profile, measured rather than
asserted. On the pinned LLVM, all 24 typed declarations canonicalize, lower
to their exact instruction heads, and assemble; the inline-PTX route
produces a byte-identical cubin to the typed route in each target tier. On
CUDA 13.3 libNVVM, the same forms compile to PTX 9.3, assemble to a cubin
byte-identical to the pinned-LLVM one, and survive `-gen-lto` plus
nvJitLink.

Verified: `check`, `probe --all --skip-terminal` (853/853 routes, all 24 new
ones lowering to the expected instruction), `check-abi-history`,
`cargo fmt --all --check`, `cargo clippy --workspace --all-targets -D
warnings`, and the cuda-intrinsics-gen (288), cuda-intrinsics (853),
mir-importer (917), mir-lower (245), dialect-nvvm (50), and cuda-device (82)
test suites.

Claude-Session: https://claude.ai/code/session_01LXYptgNnAcDSbkgyWGYQzk
Signed-off-by: abder <[email protected]>
…dware

Applies the pre-push review to the scalar f16/bf16 min/max work.

Coverage kernel (review Step 51). `compile_extended_minmax` in the
`generated_intrinsics` example enumerated all 28 pre-existing variants but
none of the 24 new ones, so nothing drove them through device codegen. All
24 are now called there, alternating the `cuda_intrinsics` and `cuda_device`
paths the way the packed block already does. This is the check that catches a
stale `generated_intrinsic_targets.rs`: without it the new stubs would fail
at device codegen with an unknown-marker error and no test would notice.

Hardware verification (review Step 44). Adds a launched
`scalar_half_minmax` kernel plus host assertions that compare raw `u16` bit
patterns, run on an sm_86 RTX A2000:

- Numeric inputs `+1.0` and `-2.0` - asymmetric and opposite-signed, so the
  `xorsign.abs` forms cannot pass by accident. All 12 results matched the ISA
  semantics, confirming `xorsign.abs` takes the magnitude min/max and the
  XOR of the input signs.
- A second launch with a NaN operand separates the plain forms from the
  `NaN` forms, which is the only input class where they differ.

The NaN case corrected an assumption rather than confirming one. PTX's
canonical NaN is `0x7FFF` - an all-ones exponent and mantissa with a clear
sign, the 16-bit analogue of the `0x7fffffff` the ISA gives for `f32` - not
the IEEE default quiet NaN (`0x7E00` for f16, `0x7FC0` for bf16) that the
test originally expected. The measured value is now pinned in the test and
recorded in both module docs.

Also from the review:

- SPDX header block on the two new files. They followed `f16x2.rs`, which is
  one of only three files in `cuda-device/src` still using the older
  `// Copyright` form; the other 29 use the block, and it is what the review
  requires for new files.
- Reciprocal `See also` links between the packed and scalar modules
  (Step 6), so `f16x2` points at `f16` and `bf16x2` at `bf16`.

Verified: `check`, `cargo fmt --all --check` in both workspaces, `cargo
clippy --workspace --all-targets -D warnings`, `RUSTDOCFLAGS='-D warnings'
cargo doc`, cuda-intrinsics-gen (288 tests), and
`scripts/smoketest.sh -o '^generated_intrinsics$'` both `--compile-only`
(verified by libNVVM) and launched on hardware.

Claude-Session: https://claude.ai/code/session_01LXYptgNnAcDSbkgyWGYQzk
Signed-off-by: abder <[email protected]>
The array length was written out as `[u16; 12]` in the kernel signature, the
device-buffer type, and the closure's return type, so adding a check meant
editing three places and keeping them in step by hand. The sibling
`f16x2_arith` example already names this kind of length; follow it.

No behaviour change; the example still passes on sm_86.

Claude-Session: https://claude.ai/code/session_01LXYptgNnAcDSbkgyWGYQzk
Signed-off-by: abder <[email protected]>
@nihalpasham nihalpasham added enhancement New feature or request intrinsics Device intrinsics and libdevice math mappings codegen Device code-generation pipeline (Rust MIR to IR to PTX) IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) labels Aug 4, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

Ran the full battery locally:

  • cuda-intrinsics-gen check reports generated outputs current, and check-abi-history confirms all 829 base entries preserved, 853 total, so the second ABI block is append-only as documented.
  • cargo test --workspace green.
  • smoketest executed generated_intrinsics on sm_120: every bit-exact assertion passes, including the measured 0x7FFF canonical NaN, and the Blackwell libNVVM variant passes too.
  • checked the bf16-ftz exclusion against the PTX ISA grammar and our pinned imported.json: those forms have no NVPTX selection pattern, so leaving them out is right (clang actually declares those builtins and they die at instruction selection).
  • on trimming the overlap: keeping all 24 is the right call. Rust has no bf16 primitive, so the real overlap is only the 4 plain/NaN f16 forms, and the intrinsic guarantees the exact instruction where the primitive goes through the optimizer.

The three-state MinMaxCarrier is a strictly better model than the packed boolean. Thanks for the thorough work, hardware-measured NaN detail included.

@nihalpasham
nihalpasham merged commit ec8d10f into NVIDIA:main Aug 4, 2026
33 checks passed
honeyspoon added a commit to honeyspoon/cuda-oxide that referenced this pull request Aug 4, 2026
… backend

Carried over from the NVIDIA#649 review, where the maintainer independently checked
a near-identical exclusion against the PTX ISA grammar rather than taking the
backend failure at face value. Doing that here changes the answer's basis.

The `ftz` and `sat` fma forms do not exist for `bf16x2` in the ISA at all.
ptxas rejects hand-written `fma.rn.ftz.bf16x2` with "Illegal modifier `.ftz`
for instruction `fma`", and accepts `fma.rn.relu.bf16x2` beside it, so the
assembler - not LLVM - is the authority. LLVM declaring the intrinsics anyway
is why instruction selection is merely what fails first. The recipe comment
and the `bf16x2` module docs now say that, so the asymmetry between six `f16x2`
fma forms and two `bf16x2` ones reads as an ISA fact rather than an omission.

Also documents the `f16x2` fma modifier set with its split floors: the four
non-ReLU forms are native at PTX ISA 4.2, while both ReLU forms require sm_80
and PTX ISA 7.0.

Verified: `check`, `probe --all --skip-terminal` (857/857), `check-abi-history`
(853 base entries preserved), 288 generator tests, `cargo fmt --all --check`,
`cargo clippy --workspace --all-targets -D warnings`, `RUSTDOCFLAGS='-D
warnings' cargo doc`, and `f16x2_arith` launched on sm_86.

Claude-Session: https://claude.ai/code/session_01LXYptgNnAcDSbkgyWGYQzk
Signed-off-by: abder <[email protected]>
nihalpasham pushed a commit that referenced this pull request Aug 5, 2026
* feat(intrinsics): add packed f16x2 fma ftz and saturating forms

Completes the `packed_alu` fma modifier coverage for `f16x2`. The family
already had `fma.rn.f16x2` and `fma.rn.relu.f16x2`; LLVM also declares the
`ftz` and `sat` combinations, each with a single tablegen selection record,
and all four lower on the pinned backend.

Adds 4 intrinsics:

- `fma_ftz_f16x2` - `fma.rn.ftz.f16x2`
- `fma_sat_f16x2` - `fma.rn.sat.f16x2`
- `fma_ftz_sat_f16x2` - `fma.rn.ftz.sat.f16x2`
- `fma_ftz_relu_f16x2` - `fma.rn.ftz.relu.f16x2`

The four `bf16x2` counterparts are excluded. LLVM declares them but the NVPTX
backend has no selection pattern, so instruction selection fails with
"Cannot select: intrinsic %llvm.nvvm.fma.rn.ftz.bf16x2"; they also carry no
tablegen selection record in the imported ledger. `packed_alu_recipe` now
returns `Option` and rejects those pairs by name, so the family fails closed
with "is outside the closed packed-ALU recipe" instead of admitting a variant
that cannot lower. That is also why the dispatcher had to become fallible
rather than panicking on an unknown pair.

Architecture floors differ inside the group and are not collapsed: `ftz`,
`sat`, and `ftz.sat` are native at PTX 4.2 / sm_53, while `ftz.relu` needs
PTX 7.0 / sm_80. The first three therefore mirror the existing `fma_f16x2`
per-backend floors exactly - PTX 6.0 / sm_70 for the pinned LLVM route, PTX
4.2 / sm_75 for libNVVM, the latter because CUDA 13.3 ptxas no longer accepts
sm_70.

Evidence is measured, not asserted, for both backend profiles. On the pinned
LLVM the inline-PTX bundles lower with every exact instruction head present
and assemble under CUDA 13.3 ptxas; independent typed calls to the
`llvm.nvvm` symbols emit the same heads. On CUDA 13.3 libNVVM the same forms
compile to PTX 9.3, assemble, and survive `-gen-lto` plus nvJitLink.

Hardware verification extends the launched `f16x2_arith` example from 9 to 14
checked operations, run on an sm_86 RTX A2000. The new cases are chosen to
discriminate rather than merely execute: a subnormal input pair
(`0x0002_0001`) is preserved by `fma_f16x2` and flushed to zero by
`fma_ftz_f16x2` and `fma_ftz_relu_f16x2`, and `2*3+7 = 13` / `4*5+11 = 31`
clamp to 1.0 under the saturating forms. All 14 pass bit-exactly.

Verified: `check`, `probe --all --skip-terminal` (833/833 routes, all four new
ones lowering to the expected instruction), `check-abi-history` (829 base
entries preserved), `cargo fmt --all --check` in all three workspaces,
`cargo clippy --workspace --all-targets -D warnings`, `RUSTDOCFLAGS='-D
warnings' cargo doc`, cuda-intrinsics-gen (288 tests), and
`scripts/smoketest.sh -o '^f16x2_arith$'` launched on hardware.

Claude-Session: https://claude.ai/code/session_01LXYptgNnAcDSbkgyWGYQzk
Signed-off-by: abder <[email protected]>

* refactor(intrinsics): thread the resolved packed-ALU recipe to the floor lookup

Two review findings on the preceding commit, neither observable in the
generated output - regeneration is byte-identical.

`packed_alu_backend_floor` re-derived the recipe it was handed a moment
earlier and used `expect` to discharge the `Option` the previous commit
introduced. Every one of its three callers already holds the resolved recipe,
so it now takes that by reference. The panic path is gone rather than argued
unreachable, and a redundant lookup goes with it.

The four new f16x2 match arms were also inserted wherever they happened to
fit, which split the relu pair and left the arm order out of step with the
enum. `FmaFtzRelu` now follows `FmaRelu`, so the arms read in enum order.

Verified: `check`, `probe --all --skip-terminal` (833/833), 288 generator
tests, `cargo fmt --all --check`, `cargo clippy --workspace --all-targets
-D warnings`, `RUSTDOCFLAGS='-D warnings' cargo doc`, and the launched
`f16x2_arith` example on sm_86.

Claude-Session: https://claude.ai/code/session_01LXYptgNnAcDSbkgyWGYQzk
Signed-off-by: abder <[email protected]>

* doc(intrinsics): justify the bf16x2 fma exclusion at the ISA, not the backend

Carried over from the #649 review, where the maintainer independently checked
a near-identical exclusion against the PTX ISA grammar rather than taking the
backend failure at face value. Doing that here changes the answer's basis.

The `ftz` and `sat` fma forms do not exist for `bf16x2` in the ISA at all.
ptxas rejects hand-written `fma.rn.ftz.bf16x2` with "Illegal modifier `.ftz`
for instruction `fma`", and accepts `fma.rn.relu.bf16x2` beside it, so the
assembler - not LLVM - is the authority. LLVM declaring the intrinsics anyway
is why instruction selection is merely what fails first. The recipe comment
and the `bf16x2` module docs now say that, so the asymmetry between six `f16x2`
fma forms and two `bf16x2` ones reads as an ISA fact rather than an omission.

Also documents the `f16x2` fma modifier set with its split floors: the four
non-ReLU forms are native at PTX ISA 4.2, while both ReLU forms require sm_80
and PTX ISA 7.0.

Verified: `check`, `probe --all --skip-terminal` (857/857), `check-abi-history`
(853 base entries preserved), 288 generator tests, `cargo fmt --all --check`,
`cargo clippy --workspace --all-targets -D warnings`, `RUSTDOCFLAGS='-D
warnings' cargo doc`, and `f16x2_arith` launched on sm_86.

Claude-Session: https://claude.ai/code/session_01LXYptgNnAcDSbkgyWGYQzk
Signed-off-by: abder <[email protected]>

---------

Signed-off-by: abder <[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) enhancement New feature or request intrinsics Device intrinsics and libdevice math mappings IR-lowering Lowering between dialects (dialect-mir to LLVM dialect)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants